Bug 4549. "Temporary" means that it's cleared in parse() or some other frequently...
[lhc/web/wiklou.git] / includes / Parser.php
1 <?php
2 /**
3 * File for Parser and related classes
4 *
5 * @package MediaWiki
6 * @subpackage Parser
7 */
8
9 /** */
10 require_once( 'Sanitizer.php' );
11 require_once( 'HttpFunctions.php' );
12
13 /**
14 * Update this version number when the ParserOutput format
15 * changes in an incompatible way, so the parser cache
16 * can automatically discard old data.
17 */
18 define( 'MW_PARSER_VERSION', '1.6.0' );
19
20 /**
21 * Variable substitution O(N^2) attack
22 *
23 * Without countermeasures, it would be possible to attack the parser by saving
24 * a page filled with a large number of inclusions of large pages. The size of
25 * the generated page would be proportional to the square of the input size.
26 * Hence, we limit the number of inclusions of any given page, thus bringing any
27 * attack back to O(N).
28 */
29
30 define( 'MAX_INCLUDE_REPEAT', 100 );
31 define( 'MAX_INCLUDE_SIZE', 1000000 ); // 1 Million
32
33 define( 'RLH_FOR_UPDATE', 1 );
34
35 # Allowed values for $mOutputType
36 define( 'OT_HTML', 1 );
37 define( 'OT_WIKI', 2 );
38 define( 'OT_MSG' , 3 );
39
40 # string parameter for extractTags which will cause it
41 # to strip HTML comments in addition to regular
42 # <XML>-style tags. This should not be anything we
43 # may want to use in wikisyntax
44 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
45
46 # Constants needed for external link processing
47 define( 'HTTP_PROTOCOLS', 'http:\/\/|https:\/\/' );
48 # Everything except bracket, space, or control characters
49 define( 'EXT_LINK_URL_CLASS', '[^][<>"\\x00-\\x20\\x7F]' );
50 # Including space
51 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x00-\\x1F\\x7F]' );
52 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
53 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
54 define( 'EXT_LINK_BRACKETED', '/\[(\b(' . wfUrlProtocols() . ')'.EXT_LINK_URL_CLASS.'+) *('.EXT_LINK_TEXT_CLASS.'*?)\]/S' );
55 define( 'EXT_IMAGE_REGEX',
56 '/^('.HTTP_PROTOCOLS.')'. # Protocol
57 '('.EXT_LINK_URL_CLASS.'+)\\/'. # Hostname and path
58 '('.EXT_IMAGE_FNAME_CLASS.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS.')$/S' # Filename
59 );
60
61 /**
62 * PHP Parser
63 *
64 * Processes wiki markup
65 *
66 * <pre>
67 * There are three main entry points into the Parser class:
68 * parse()
69 * produces HTML output
70 * preSaveTransform().
71 * produces altered wiki markup.
72 * transformMsg()
73 * performs brace substitution on MediaWiki messages
74 *
75 * Globals used:
76 * objects: $wgLang
77 *
78 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
79 *
80 * settings:
81 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
82 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
83 * $wgLocaltimezone, $wgAllowSpecialInclusion*
84 *
85 * * only within ParserOptions
86 * </pre>
87 *
88 * @package MediaWiki
89 */
90 class Parser
91 {
92 /**#@+
93 * @access private
94 */
95 # Persistent:
96 var $mTagHooks;
97
98 # Cleared with clearState():
99 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
100 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
101 var $mInterwikiLinkHolders, $mLinkHolders, $mUniqPrefix;
102 var $mTemplates, // cache of already loaded templates, avoids
103 // multiple SQL queries for the same string
104 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
105 // in this path. Used for loop detection.
106
107 # Temporary
108 # These are variables reset at least once per parse regardless of $clearState
109 var $mOptions, // ParserOptions object
110 $mTitle, // Title context, used for self-link rendering and similar things
111 $mOutputType, // Output type, one of the OT_xxx constants
112 $mRevisionId; // ID to display in {{REVISIONID}} tags
113
114 /**#@-*/
115
116 /**
117 * Constructor
118 *
119 * @access public
120 */
121 function Parser() {
122 $this->mTagHooks = array();
123 $this->clearState();
124 }
125
126 /**
127 * Clear Parser state
128 *
129 * @access private
130 */
131 function clearState() {
132 $this->mOutput = new ParserOutput;
133 $this->mAutonumber = 0;
134 $this->mLastSection = '';
135 $this->mDTopen = false;
136 $this->mVariables = false;
137 $this->mIncludeCount = array();
138 $this->mStripState = array();
139 $this->mArgStack = array();
140 $this->mInPre = false;
141 $this->mInterwikiLinkHolders = array(
142 'texts' => array(),
143 'titles' => array()
144 );
145 $this->mLinkHolders = array(
146 'namespaces' => array(),
147 'dbkeys' => array(),
148 'queries' => array(),
149 'texts' => array(),
150 'titles' => array()
151 );
152 $this->mRevisionId = null;
153 $this->mUniqPrefix = 'UNIQ' . Parser::getRandomString();
154
155 # Clear these on every parse, bug 4549
156 $this->mTemplates = array();
157 $this->mTemplatePath = array();
158
159 wfRunHooks( 'ParserClearState', array( &$this ) );
160 }
161
162 /**
163 * Accessor for mUniqPrefix.
164 *
165 * @access public
166 */
167 function UniqPrefix() {
168 return $this->mUniqPrefix;
169 }
170
171 /**
172 * Convert wikitext to HTML
173 * Do not call this function recursively.
174 *
175 * @access private
176 * @param string $text Text we want to parse
177 * @param Title &$title A title object
178 * @param array $options
179 * @param boolean $linestart
180 * @param boolean $clearState
181 * @param int $revid number to pass in {{REVISIONID}}
182 * @return ParserOutput a ParserOutput
183 */
184 function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
185 /**
186 * First pass--just handle <nowiki> sections, pass the rest off
187 * to internalParse() which does all the real work.
188 */
189
190 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
191 $fname = 'Parser::parse';
192 wfProfileIn( $fname );
193
194 if ( $clearState ) {
195 $this->clearState();
196 }
197
198 $this->mOptions = $options;
199 $this->mTitle =& $title;
200 $this->mRevisionId = $revid;
201 $this->mOutputType = OT_HTML;
202
203 $this->mStripState = NULL;
204
205 //$text = $this->strip( $text, $this->mStripState );
206 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
207 $x =& $this->mStripState;
208
209 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
210 $text = $this->strip( $text, $x );
211 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
212
213 # Hook to suspend the parser in this state
214 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$x ) ) ) {
215 wfProfileOut( $fname );
216 return $text ;
217 }
218
219 $text = $this->internalParse( $text );
220
221 $text = $this->unstrip( $text, $this->mStripState );
222
223 # Clean up special characters, only run once, next-to-last before doBlockLevels
224 $fixtags = array(
225 # french spaces, last one Guillemet-left
226 # only if there is something before the space
227 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1&nbsp;\\2',
228 # french spaces, Guillemet-right
229 '/(\\302\\253) /' => '\\1&nbsp;',
230 '/<center *>(.*)<\\/center *>/i' => '<div class="center">\\1</div>',
231 );
232 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
233
234 # only once and last
235 $text = $this->doBlockLevels( $text, $linestart );
236
237 $this->replaceLinkHolders( $text );
238
239 # the position of the convert() call should not be changed. it
240 # assumes that the links are all replaces and the only thing left
241 # is the <nowiki> mark.
242 $text = $wgContLang->convert($text);
243 $this->mOutput->setTitleText($wgContLang->getParsedTitle());
244
245 $text = $this->unstripNoWiki( $text, $this->mStripState );
246
247 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
248
249 $text = Sanitizer::normalizeCharReferences( $text );
250
251 if (($wgUseTidy and $this->mOptions->mTidy) or $wgAlwaysUseTidy) {
252 $text = Parser::tidy($text);
253 }
254
255 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
256
257 $this->mOutput->setText( $text );
258 wfProfileOut( $fname );
259
260 return $this->mOutput;
261 }
262
263 /**
264 * Get a random string
265 *
266 * @access private
267 * @static
268 */
269 function getRandomString() {
270 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
271 }
272
273 /**
274 * Replaces all occurrences of <$tag>content</$tag> in the text
275 * with a random marker and returns the new text. the output parameter
276 * $content will be an associative array filled with data on the form
277 * $unique_marker => content.
278 *
279 * If $content is already set, the additional entries will be appended
280 * If $tag is set to STRIP_COMMENTS, the function will extract
281 * <!-- HTML comments -->
282 *
283 * @access private
284 * @static
285 */
286 function extractTagsAndParams($tag, $text, &$content, &$tags, &$params, $uniq_prefix = ''){
287 $rnd = $uniq_prefix . '-' . $tag . Parser::getRandomString();
288 if ( !$content ) {
289 $content = array( );
290 }
291 $n = 1;
292 $stripped = '';
293
294 if ( !$tags ) {
295 $tags = array( );
296 }
297
298 if ( !$params ) {
299 $params = array( );
300 }
301
302 if( $tag == STRIP_COMMENTS ) {
303 $start = '/<!--()()/';
304 $end = '/-->/';
305 } else {
306 $start = "/<$tag(\\s+[^\\/>]*|\\s*)(\\/?)>/i";
307 $end = "/<\\/$tag\\s*>/i";
308 }
309
310 while ( '' != $text ) {
311 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE );
312 $stripped .= $p[0];
313 if( count( $p ) < 4 ) {
314 break;
315 }
316 $attributes = $p[1];
317 $empty = $p[2];
318 $inside = $p[3];
319
320 $marker = $rnd . sprintf('%08X', $n++);
321 $stripped .= $marker;
322
323 $tags[$marker] = "<$tag$attributes$empty>";
324 $params[$marker] = Sanitizer::decodeTagAttributes( $attributes );
325
326 if ( $empty === '/' ) {
327 // Empty element tag, <tag />
328 $content[$marker] = null;
329 $text = $inside;
330 } else {
331 $q = preg_split( $end, $inside, 2 );
332 $content[$marker] = $q[0];
333 if( count( $q ) < 2 ) {
334 # No end tag -- let it run out to the end of the text.
335 break;
336 } else {
337 $text = $q[1];
338 }
339 }
340 }
341 return $stripped;
342 }
343
344 /**
345 * Wrapper function for extractTagsAndParams
346 * for cases where $tags and $params isn't needed
347 * i.e. where tags will never have params, like <nowiki>
348 *
349 * @access private
350 * @static
351 */
352 function extractTags( $tag, $text, &$content, $uniq_prefix = '' ) {
353 $dummy_tags = array();
354 $dummy_params = array();
355
356 return Parser::extractTagsAndParams( $tag, $text, $content,
357 $dummy_tags, $dummy_params, $uniq_prefix );
358 }
359
360 /**
361 * Strips and renders nowiki, pre, math, hiero
362 * If $render is set, performs necessary rendering operations on plugins
363 * Returns the text, and fills an array with data needed in unstrip()
364 * If the $state is already a valid strip state, it adds to the state
365 *
366 * @param bool $stripcomments when set, HTML comments <!-- like this -->
367 * will be stripped in addition to other tags. This is important
368 * for section editing, where these comments cause confusion when
369 * counting the sections in the wikisource
370 *
371 * @access private
372 */
373 function strip( $text, &$state, $stripcomments = false ) {
374 $render = ($this->mOutputType == OT_HTML);
375 $html_content = array();
376 $nowiki_content = array();
377 $math_content = array();
378 $pre_content = array();
379 $comment_content = array();
380 $ext_content = array();
381 $ext_tags = array();
382 $ext_params = array();
383 $gallery_content = array();
384
385 # Replace any instances of the placeholders
386 $uniq_prefix = $this->mUniqPrefix;
387 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
388
389 # html
390 global $wgRawHtml;
391 if( $wgRawHtml ) {
392 $text = Parser::extractTags('html', $text, $html_content, $uniq_prefix);
393 foreach( $html_content as $marker => $content ) {
394 if ($render ) {
395 # Raw and unchecked for validity.
396 $html_content[$marker] = $content;
397 } else {
398 $html_content[$marker] = '<html>'.$content.'</html>';
399 }
400 }
401 }
402
403 # nowiki
404 $text = Parser::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
405 foreach( $nowiki_content as $marker => $content ) {
406 if( $render ){
407 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
408 } else {
409 $nowiki_content[$marker] = '<nowiki>'.$content.'</nowiki>';
410 }
411 }
412
413 # math
414 if( $this->mOptions->getUseTeX() ) {
415 $text = Parser::extractTags('math', $text, $math_content, $uniq_prefix);
416 foreach( $math_content as $marker => $content ){
417 if( $render ) {
418 $math_content[$marker] = renderMath( $content );
419 } else {
420 $math_content[$marker] = '<math>'.$content.'</math>';
421 }
422 }
423 }
424
425 # pre
426 $text = Parser::extractTags('pre', $text, $pre_content, $uniq_prefix);
427 foreach( $pre_content as $marker => $content ){
428 if( $render ){
429 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
430 } else {
431 $pre_content[$marker] = '<pre>'.$content.'</pre>';
432 }
433 }
434
435 # gallery
436 $text = Parser::extractTags('gallery', $text, $gallery_content, $uniq_prefix);
437 foreach( $gallery_content as $marker => $content ) {
438 require_once( 'ImageGallery.php' );
439 if ( $render ) {
440 $gallery_content[$marker] = $this->renderImageGallery( $content );
441 } else {
442 $gallery_content[$marker] = '<gallery>'.$content.'</gallery>';
443 }
444 }
445
446 # Comments
447 if($stripcomments) {
448 $text = Parser::extractTags(STRIP_COMMENTS, $text, $comment_content, $uniq_prefix);
449 foreach( $comment_content as $marker => $content ){
450 $comment_content[$marker] = '<!--'.$content.'-->';
451 }
452 }
453
454 # Extensions
455 foreach ( $this->mTagHooks as $tag => $callback ) {
456 $ext_content[$tag] = array();
457 $text = Parser::extractTagsAndParams( $tag, $text, $ext_content[$tag],
458 $ext_tags[$tag], $ext_params[$tag], $uniq_prefix );
459 foreach( $ext_content[$tag] as $marker => $content ) {
460 $full_tag = $ext_tags[$tag][$marker];
461 $params = $ext_params[$tag][$marker];
462 if ( $render )
463 $ext_content[$tag][$marker] = call_user_func_array( $callback, array( $content, $params, &$this ) );
464 else {
465 if ( is_null( $content ) ) {
466 // Empty element tag
467 $ext_content[$tag][$marker] = $full_tag;
468 } else {
469 $ext_content[$tag][$marker] = "$full_tag$content</$tag>";
470 }
471 }
472 }
473 }
474
475 # Merge state with the pre-existing state, if there is one
476 if ( $state ) {
477 $state['html'] = $state['html'] + $html_content;
478 $state['nowiki'] = $state['nowiki'] + $nowiki_content;
479 $state['math'] = $state['math'] + $math_content;
480 $state['pre'] = $state['pre'] + $pre_content;
481 $state['comment'] = $state['comment'] + $comment_content;
482 $state['gallery'] = $state['gallery'] + $gallery_content;
483
484 foreach( $ext_content as $tag => $array ) {
485 if ( array_key_exists( $tag, $state ) ) {
486 $state[$tag] = $state[$tag] + $array;
487 }
488 }
489 } else {
490 $state = array(
491 'html' => $html_content,
492 'nowiki' => $nowiki_content,
493 'math' => $math_content,
494 'pre' => $pre_content,
495 'comment' => $comment_content,
496 'gallery' => $gallery_content,
497 ) + $ext_content;
498 }
499 return $text;
500 }
501
502 /**
503 * restores pre, math, and hiero removed by strip()
504 *
505 * always call unstripNoWiki() after this one
506 * @access private
507 */
508 function unstrip( $text, &$state ) {
509 if ( !is_array( $state ) ) {
510 return $text;
511 }
512
513 # Must expand in reverse order, otherwise nested tags will be corrupted
514 foreach( array_reverse( $state, true ) as $tag => $contentDict ) {
515 if( $tag != 'nowiki' && $tag != 'html' ) {
516 foreach( array_reverse( $contentDict, true ) as $uniq => $content ) {
517 $text = str_replace( $uniq, $content, $text );
518 }
519 }
520 }
521
522 return $text;
523 }
524
525 /**
526 * always call this after unstrip() to preserve the order
527 *
528 * @access private
529 */
530 function unstripNoWiki( $text, &$state ) {
531 if ( !is_array( $state ) ) {
532 return $text;
533 }
534
535 # Must expand in reverse order, otherwise nested tags will be corrupted
536 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
537 $text = str_replace( key( $state['nowiki'] ), $content, $text );
538 }
539
540 global $wgRawHtml;
541 if ($wgRawHtml) {
542 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
543 $text = str_replace( key( $state['html'] ), $content, $text );
544 }
545 }
546
547 return $text;
548 }
549
550 /**
551 * Add an item to the strip state
552 * Returns the unique tag which must be inserted into the stripped text
553 * The tag will be replaced with the original text in unstrip()
554 *
555 * @access private
556 */
557 function insertStripItem( $text, &$state ) {
558 $rnd = $this->mUniqPrefix . '-item' . Parser::getRandomString();
559 if ( !$state ) {
560 $state = array(
561 'html' => array(),
562 'nowiki' => array(),
563 'math' => array(),
564 'pre' => array(),
565 'comment' => array(),
566 'gallery' => array(),
567 );
568 }
569 $state['item'][$rnd] = $text;
570 return $rnd;
571 }
572
573 /**
574 * Interface with html tidy, used if $wgUseTidy = true.
575 * If tidy isn't able to correct the markup, the original will be
576 * returned in all its glory with a warning comment appended.
577 *
578 * Either the external tidy program or the in-process tidy extension
579 * will be used depending on availability. Override the default
580 * $wgTidyInternal setting to disable the internal if it's not working.
581 *
582 * @param string $text Hideous HTML input
583 * @return string Corrected HTML output
584 * @access public
585 * @static
586 */
587 function tidy( $text ) {
588 global $wgTidyInternal;
589 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
590 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
591 '<head><title>test</title></head><body>'.$text.'</body></html>';
592 if( $wgTidyInternal ) {
593 $correctedtext = Parser::internalTidy( $wrappedtext );
594 } else {
595 $correctedtext = Parser::externalTidy( $wrappedtext );
596 }
597 if( is_null( $correctedtext ) ) {
598 wfDebug( "Tidy error detected!\n" );
599 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
600 }
601 return $correctedtext;
602 }
603
604 /**
605 * Spawn an external HTML tidy process and get corrected markup back from it.
606 *
607 * @access private
608 * @static
609 */
610 function externalTidy( $text ) {
611 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
612 $fname = 'Parser::externalTidy';
613 wfProfileIn( $fname );
614
615 $cleansource = '';
616 $opts = ' -utf8';
617
618 $descriptorspec = array(
619 0 => array('pipe', 'r'),
620 1 => array('pipe', 'w'),
621 2 => array('file', '/dev/null', 'a')
622 );
623 $pipes = array();
624 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
625 if (is_resource($process)) {
626 fwrite($pipes[0], $text);
627 fclose($pipes[0]);
628 while (!feof($pipes[1])) {
629 $cleansource .= fgets($pipes[1], 1024);
630 }
631 fclose($pipes[1]);
632 proc_close($process);
633 }
634
635 wfProfileOut( $fname );
636
637 if( $cleansource == '' && $text != '') {
638 // Some kind of error happened, so we couldn't get the corrected text.
639 // Just give up; we'll use the source text and append a warning.
640 return null;
641 } else {
642 return $cleansource;
643 }
644 }
645
646 /**
647 * Use the HTML tidy PECL extension to use the tidy library in-process,
648 * saving the overhead of spawning a new process. Currently written to
649 * the PHP 4.3.x version of the extension, may not work on PHP 5.
650 *
651 * 'pear install tidy' should be able to compile the extension module.
652 *
653 * @access private
654 * @static
655 */
656 function internalTidy( $text ) {
657 global $wgTidyConf;
658 $fname = 'Parser::internalTidy';
659 wfProfileIn( $fname );
660
661 tidy_load_config( $wgTidyConf );
662 tidy_set_encoding( 'utf8' );
663 tidy_parse_string( $text );
664 tidy_clean_repair();
665 if( tidy_get_status() == 2 ) {
666 // 2 is magic number for fatal error
667 // http://www.php.net/manual/en/function.tidy-get-status.php
668 $cleansource = null;
669 } else {
670 $cleansource = tidy_get_output();
671 }
672 wfProfileOut( $fname );
673 return $cleansource;
674 }
675
676 /**
677 * parse the wiki syntax used to render tables
678 *
679 * @access private
680 */
681 function doTableStuff ( $t ) {
682 $fname = 'Parser::doTableStuff';
683 wfProfileIn( $fname );
684
685 $t = explode ( "\n" , $t ) ;
686 $td = array () ; # Is currently a td tag open?
687 $ltd = array () ; # Was it TD or TH?
688 $tr = array () ; # Is currently a tr tag open?
689 $ltr = array () ; # tr attributes
690 $indent_level = 0; # indent level of the table
691 foreach ( $t AS $k => $x )
692 {
693 $x = trim ( $x ) ;
694 $fc = substr ( $x , 0 , 1 ) ;
695 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
696 $indent_level = strlen( $matches[1] );
697
698 $attributes = $this->unstripForHTML( $matches[2] );
699
700 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
701 '<table' . Sanitizer::fixTagAttributes ( $attributes, 'table' ) . '>' ;
702 array_push ( $td , false ) ;
703 array_push ( $ltd , '' ) ;
704 array_push ( $tr , false ) ;
705 array_push ( $ltr , '' ) ;
706 }
707 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
708 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
709 $z = "</table>" . substr ( $x , 2);
710 $l = array_pop ( $ltd ) ;
711 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
712 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
713 array_pop ( $ltr ) ;
714 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
715 }
716 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
717 $x = substr ( $x , 1 ) ;
718 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
719 $z = '' ;
720 $l = array_pop ( $ltd ) ;
721 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
722 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
723 array_pop ( $ltr ) ;
724 $t[$k] = $z ;
725 array_push ( $tr , false ) ;
726 array_push ( $td , false ) ;
727 array_push ( $ltd , '' ) ;
728 $attributes = $this->unstripForHTML( $x );
729 array_push ( $ltr , Sanitizer::fixTagAttributes ( $attributes, 'tr' ) ) ;
730 }
731 else if ( '|' == $fc || '!' == $fc || '|+' == substr ( $x , 0 , 2 ) ) { # Caption
732 # $x is a table row
733 if ( '|+' == substr ( $x , 0 , 2 ) ) {
734 $fc = '+' ;
735 $x = substr ( $x , 1 ) ;
736 }
737 $after = substr ( $x , 1 ) ;
738 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
739 $after = explode ( '||' , $after ) ;
740 $t[$k] = '' ;
741
742 # Loop through each table cell
743 foreach ( $after AS $theline )
744 {
745 $z = '' ;
746 if ( $fc != '+' )
747 {
748 $tra = array_pop ( $ltr ) ;
749 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
750 array_push ( $tr , true ) ;
751 array_push ( $ltr , '' ) ;
752 }
753
754 $l = array_pop ( $ltd ) ;
755 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
756 if ( $fc == '|' ) $l = 'td' ;
757 else if ( $fc == '!' ) $l = 'th' ;
758 else if ( $fc == '+' ) $l = 'caption' ;
759 else $l = '' ;
760 array_push ( $ltd , $l ) ;
761
762 # Cell parameters
763 $y = explode ( '|' , $theline , 2 ) ;
764 # Note that a '|' inside an invalid link should not
765 # be mistaken as delimiting cell parameters
766 if ( strpos( $y[0], '[[' ) !== false ) {
767 $y = array ($theline);
768 }
769 if ( count ( $y ) == 1 )
770 $y = "{$z}<{$l}>{$y[0]}" ;
771 else {
772 $attributes = $this->unstripForHTML( $y[0] );
773 $y = "{$z}<{$l}".Sanitizer::fixTagAttributes($attributes, $l).">{$y[1]}" ;
774 }
775 $t[$k] .= $y ;
776 array_push ( $td , true ) ;
777 }
778 }
779 }
780
781 # Closing open td, tr && table
782 while ( count ( $td ) > 0 )
783 {
784 if ( array_pop ( $td ) ) $t[] = '</td>' ;
785 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
786 $t[] = '</table>' ;
787 }
788
789 $t = implode ( "\n" , $t ) ;
790 wfProfileOut( $fname );
791 return $t ;
792 }
793
794 /**
795 * Helper function for parse() that transforms wiki markup into
796 * HTML. Only called for $mOutputType == OT_HTML.
797 *
798 * @access private
799 */
800 function internalParse( $text ) {
801 global $wgContLang;
802 $args = array();
803 $isMain = true;
804 $fname = 'Parser::internalParse';
805 wfProfileIn( $fname );
806
807 # Remove <noinclude> tags and <includeonly> sections
808 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
809 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
810 $text = preg_replace( '/<includeonly>.*?<\/includeonly>/s', '', $text );
811
812 $text = Sanitizer::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
813 $text = $this->replaceVariables( $text, $args );
814
815 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
816
817 $text = $this->doHeadings( $text );
818 if($this->mOptions->getUseDynamicDates()) {
819 $df =& DateFormatter::getInstance();
820 $text = $df->reformat( $this->mOptions->getDateFormat(), $text );
821 }
822 $text = $this->doAllQuotes( $text );
823 $text = $this->replaceInternalLinks( $text );
824 $text = $this->replaceExternalLinks( $text );
825
826 # replaceInternalLinks may sometimes leave behind
827 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
828 $text = str_replace($this->mUniqPrefix."NOPARSE", "", $text);
829
830 $text = $this->doMagicLinks( $text );
831 $text = $this->doTableStuff( $text );
832 $text = $this->formatHeadings( $text, $isMain );
833
834 wfProfileOut( $fname );
835 return $text;
836 }
837
838 /**
839 * Replace special strings like "ISBN xxx" and "RFC xxx" with
840 * magic external links.
841 *
842 * @access private
843 */
844 function &doMagicLinks( &$text ) {
845 $text = $this->magicISBN( $text );
846 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
847 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
848 return $text;
849 }
850
851 /**
852 * Parse headers and return html
853 *
854 * @access private
855 */
856 function doHeadings( $text ) {
857 $fname = 'Parser::doHeadings';
858 wfProfileIn( $fname );
859 for ( $i = 6; $i >= 1; --$i ) {
860 $h = str_repeat( '=', $i );
861 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
862 "<h{$i}>\\1</h{$i}>\\2", $text );
863 }
864 wfProfileOut( $fname );
865 return $text;
866 }
867
868 /**
869 * Replace single quotes with HTML markup
870 * @access private
871 * @return string the altered text
872 */
873 function doAllQuotes( $text ) {
874 $fname = 'Parser::doAllQuotes';
875 wfProfileIn( $fname );
876 $outtext = '';
877 $lines = explode( "\n", $text );
878 foreach ( $lines as $line ) {
879 $outtext .= $this->doQuotes ( $line ) . "\n";
880 }
881 $outtext = substr($outtext, 0,-1);
882 wfProfileOut( $fname );
883 return $outtext;
884 }
885
886 /**
887 * Helper function for doAllQuotes()
888 * @access private
889 */
890 function doQuotes( $text ) {
891 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE );
892 if ( count( $arr ) == 1 )
893 return $text;
894 else
895 {
896 # First, do some preliminary work. This may shift some apostrophes from
897 # being mark-up to being text. It also counts the number of occurrences
898 # of bold and italics mark-ups.
899 $i = 0;
900 $numbold = 0;
901 $numitalics = 0;
902 foreach ( $arr as $r )
903 {
904 if ( ( $i % 2 ) == 1 )
905 {
906 # If there are ever four apostrophes, assume the first is supposed to
907 # be text, and the remaining three constitute mark-up for bold text.
908 if ( strlen( $arr[$i] ) == 4 )
909 {
910 $arr[$i-1] .= "'";
911 $arr[$i] = "'''";
912 }
913 # If there are more than 5 apostrophes in a row, assume they're all
914 # text except for the last 5.
915 else if ( strlen( $arr[$i] ) > 5 )
916 {
917 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
918 $arr[$i] = "'''''";
919 }
920 # Count the number of occurrences of bold and italics mark-ups.
921 # We are not counting sequences of five apostrophes.
922 if ( strlen( $arr[$i] ) == 2 ) $numitalics++; else
923 if ( strlen( $arr[$i] ) == 3 ) $numbold++; else
924 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++; $numbold++; }
925 }
926 $i++;
927 }
928
929 # If there is an odd number of both bold and italics, it is likely
930 # that one of the bold ones was meant to be an apostrophe followed
931 # by italics. Which one we cannot know for certain, but it is more
932 # likely to be one that has a single-letter word before it.
933 if ( ( $numbold % 2 == 1 ) && ( $numitalics % 2 == 1 ) )
934 {
935 $i = 0;
936 $firstsingleletterword = -1;
937 $firstmultiletterword = -1;
938 $firstspace = -1;
939 foreach ( $arr as $r )
940 {
941 if ( ( $i % 2 == 1 ) and ( strlen( $r ) == 3 ) )
942 {
943 $x1 = substr ($arr[$i-1], -1);
944 $x2 = substr ($arr[$i-1], -2, 1);
945 if ($x1 == ' ') {
946 if ($firstspace == -1) $firstspace = $i;
947 } else if ($x2 == ' ') {
948 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
949 } else {
950 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
951 }
952 }
953 $i++;
954 }
955
956 # If there is a single-letter word, use it!
957 if ($firstsingleletterword > -1)
958 {
959 $arr [ $firstsingleletterword ] = "''";
960 $arr [ $firstsingleletterword-1 ] .= "'";
961 }
962 # If not, but there's a multi-letter word, use that one.
963 else if ($firstmultiletterword > -1)
964 {
965 $arr [ $firstmultiletterword ] = "''";
966 $arr [ $firstmultiletterword-1 ] .= "'";
967 }
968 # ... otherwise use the first one that has neither.
969 # (notice that it is possible for all three to be -1 if, for example,
970 # there is only one pentuple-apostrophe in the line)
971 else if ($firstspace > -1)
972 {
973 $arr [ $firstspace ] = "''";
974 $arr [ $firstspace-1 ] .= "'";
975 }
976 }
977
978 # Now let's actually convert our apostrophic mush to HTML!
979 $output = '';
980 $buffer = '';
981 $state = '';
982 $i = 0;
983 foreach ($arr as $r)
984 {
985 if (($i % 2) == 0)
986 {
987 if ($state == 'both')
988 $buffer .= $r;
989 else
990 $output .= $r;
991 }
992 else
993 {
994 if (strlen ($r) == 2)
995 {
996 if ($state == 'i')
997 { $output .= '</i>'; $state = ''; }
998 else if ($state == 'bi')
999 { $output .= '</i>'; $state = 'b'; }
1000 else if ($state == 'ib')
1001 { $output .= '</b></i><b>'; $state = 'b'; }
1002 else if ($state == 'both')
1003 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1004 else # $state can be 'b' or ''
1005 { $output .= '<i>'; $state .= 'i'; }
1006 }
1007 else if (strlen ($r) == 3)
1008 {
1009 if ($state == 'b')
1010 { $output .= '</b>'; $state = ''; }
1011 else if ($state == 'bi')
1012 { $output .= '</i></b><i>'; $state = 'i'; }
1013 else if ($state == 'ib')
1014 { $output .= '</b>'; $state = 'i'; }
1015 else if ($state == 'both')
1016 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1017 else # $state can be 'i' or ''
1018 { $output .= '<b>'; $state .= 'b'; }
1019 }
1020 else if (strlen ($r) == 5)
1021 {
1022 if ($state == 'b')
1023 { $output .= '</b><i>'; $state = 'i'; }
1024 else if ($state == 'i')
1025 { $output .= '</i><b>'; $state = 'b'; }
1026 else if ($state == 'bi')
1027 { $output .= '</i></b>'; $state = ''; }
1028 else if ($state == 'ib')
1029 { $output .= '</b></i>'; $state = ''; }
1030 else if ($state == 'both')
1031 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1032 else # ($state == '')
1033 { $buffer = ''; $state = 'both'; }
1034 }
1035 }
1036 $i++;
1037 }
1038 # Now close all remaining tags. Notice that the order is important.
1039 if ($state == 'b' || $state == 'ib')
1040 $output .= '</b>';
1041 if ($state == 'i' || $state == 'bi' || $state == 'ib')
1042 $output .= '</i>';
1043 if ($state == 'bi')
1044 $output .= '</b>';
1045 if ($state == 'both')
1046 $output .= '<b><i>'.$buffer.'</i></b>';
1047 return $output;
1048 }
1049 }
1050
1051 /**
1052 * Replace external links
1053 *
1054 * Note: this is all very hackish and the order of execution matters a lot.
1055 * Make sure to run maintenance/parserTests.php if you change this code.
1056 *
1057 * @access private
1058 */
1059 function replaceExternalLinks( $text ) {
1060 global $wgContLang;
1061 $fname = 'Parser::replaceExternalLinks';
1062 wfProfileIn( $fname );
1063
1064 $sk =& $this->mOptions->getSkin();
1065
1066 $bits = preg_split( EXT_LINK_BRACKETED, $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1067
1068 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1069
1070 $i = 0;
1071 while ( $i<count( $bits ) ) {
1072 $url = $bits[$i++];
1073 $protocol = $bits[$i++];
1074 $text = $bits[$i++];
1075 $trail = $bits[$i++];
1076
1077 # The characters '<' and '>' (which were escaped by
1078 # removeHTMLtags()) should not be included in
1079 # URLs, per RFC 2396.
1080 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE)) {
1081 $text = substr($url, $m2[0][1]) . ' ' . $text;
1082 $url = substr($url, 0, $m2[0][1]);
1083 }
1084
1085 # If the link text is an image URL, replace it with an <img> tag
1086 # This happened by accident in the original parser, but some people used it extensively
1087 $img = $this->maybeMakeExternalImage( $text );
1088 if ( $img !== false ) {
1089 $text = $img;
1090 }
1091
1092 $dtrail = '';
1093
1094 # Set linktype for CSS - if URL==text, link is essentially free
1095 $linktype = ($text == $url) ? 'free' : 'text';
1096
1097 # No link text, e.g. [http://domain.tld/some.link]
1098 if ( $text == '' ) {
1099 # Autonumber if allowed
1100 if ( strpos( HTTP_PROTOCOLS, str_replace('/','\/', $protocol) ) !== false ) {
1101 $text = '[' . ++$this->mAutonumber . ']';
1102 $linktype = 'autonumber';
1103 } else {
1104 # Otherwise just use the URL
1105 $text = htmlspecialchars( $url );
1106 $linktype = 'free';
1107 }
1108 } else {
1109 # Have link text, e.g. [http://domain.tld/some.link text]s
1110 # Check for trail
1111 list( $dtrail, $trail ) = Linker::splitTrail( $trail );
1112 }
1113
1114 $text = $wgContLang->markNoConversion($text);
1115
1116 # Replace &amp; from obsolete syntax with &.
1117 # All HTML entities will be escaped by makeExternalLink()
1118 $url = str_replace( '&amp;', '&', $url );
1119 # Replace unnecessary URL escape codes with the referenced character
1120 # This prevents spammers from hiding links from the filters
1121 $url = Parser::replaceUnusualEscapes( $url );
1122
1123 # Process the trail (i.e. everything after this link up until start of the next link),
1124 # replacing any non-bracketed links
1125 $trail = $this->replaceFreeExternalLinks( $trail );
1126
1127 # Use the encoded URL
1128 # This means that users can paste URLs directly into the text
1129 # Funny characters like &ouml; aren't valid in URLs anyway
1130 # This was changed in August 2004
1131 $s .= $sk->makeExternalLink( $url, $text, false, $linktype ) . $dtrail . $trail;
1132
1133 # Register link in the output object
1134 $this->mOutput->addExternalLink( $url );
1135 }
1136
1137 wfProfileOut( $fname );
1138 return $s;
1139 }
1140
1141 /**
1142 * Replace anything that looks like a URL with a link
1143 * @access private
1144 */
1145 function replaceFreeExternalLinks( $text ) {
1146 global $wgContLang;
1147 $fname = 'Parser::replaceFreeExternalLinks';
1148 wfProfileIn( $fname );
1149
1150 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1151 $s = array_shift( $bits );
1152 $i = 0;
1153
1154 $sk =& $this->mOptions->getSkin();
1155
1156 while ( $i < count( $bits ) ){
1157 $protocol = $bits[$i++];
1158 $remainder = $bits[$i++];
1159
1160 if ( preg_match( '/^('.EXT_LINK_URL_CLASS.'+)(.*)$/s', $remainder, $m ) ) {
1161 # Found some characters after the protocol that look promising
1162 $url = $protocol . $m[1];
1163 $trail = $m[2];
1164
1165 # The characters '<' and '>' (which were escaped by
1166 # removeHTMLtags()) should not be included in
1167 # URLs, per RFC 2396.
1168 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE)) {
1169 $trail = substr($url, $m2[0][1]) . $trail;
1170 $url = substr($url, 0, $m2[0][1]);
1171 }
1172
1173 # Move trailing punctuation to $trail
1174 $sep = ',;\.:!?';
1175 # If there is no left bracket, then consider right brackets fair game too
1176 if ( strpos( $url, '(' ) === false ) {
1177 $sep .= ')';
1178 }
1179
1180 $numSepChars = strspn( strrev( $url ), $sep );
1181 if ( $numSepChars ) {
1182 $trail = substr( $url, -$numSepChars ) . $trail;
1183 $url = substr( $url, 0, -$numSepChars );
1184 }
1185
1186 # Replace &amp; from obsolete syntax with &.
1187 # All HTML entities will be escaped by makeExternalLink()
1188 # or maybeMakeExternalImage()
1189 $url = str_replace( '&amp;', '&', $url );
1190 # Replace unnecessary URL escape codes with their equivalent characters
1191 $url = Parser::replaceUnusualEscapes( $url );
1192
1193 # Is this an external image?
1194 $text = $this->maybeMakeExternalImage( $url );
1195 if ( $text === false ) {
1196 # Not an image, make a link
1197 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free' );
1198 # Register it in the output object
1199 $this->mOutput->addExternalLink( $url );
1200 }
1201 $s .= $text . $trail;
1202 } else {
1203 $s .= $protocol . $remainder;
1204 }
1205 }
1206 wfProfileOut( $fname );
1207 return $s;
1208 }
1209
1210 /**
1211 * Replace unusual URL escape codes with their equivalent characters
1212 * @param string
1213 * @return string
1214 * @static
1215 */
1216 function replaceUnusualEscapes( $url ) {
1217 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1218 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1219 }
1220
1221 /**
1222 * Callback function used in replaceUnusualEscapes().
1223 * Replaces unusual URL escape codes with their equivalent character
1224 * @static
1225 * @access private
1226 */
1227 function replaceUnusualEscapesCallback( $matches ) {
1228 $char = urldecode( $matches[0] );
1229 $ord = ord( $char );
1230 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1231 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1232 // No, shouldn't be escaped
1233 return $char;
1234 } else {
1235 // Yes, leave it escaped
1236 return $matches[0];
1237 }
1238 }
1239
1240 /**
1241 * make an image if it's allowed, either through the global
1242 * option or through the exception
1243 * @access private
1244 */
1245 function maybeMakeExternalImage( $url ) {
1246 $sk =& $this->mOptions->getSkin();
1247 $imagesfrom = $this->mOptions->getAllowExternalImagesFrom();
1248 $imagesexception = !empty($imagesfrom);
1249 $text = false;
1250 if ( $this->mOptions->getAllowExternalImages()
1251 || ( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1252 if ( preg_match( EXT_IMAGE_REGEX, $url ) ) {
1253 # Image found
1254 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1255 }
1256 }
1257 return $text;
1258 }
1259
1260 /**
1261 * Process [[ ]] wikilinks
1262 *
1263 * @access private
1264 */
1265 function replaceInternalLinks( $s ) {
1266 global $wgContLang;
1267 static $fname = 'Parser::replaceInternalLinks' ;
1268
1269 wfProfileIn( $fname );
1270
1271 wfProfileIn( $fname.'-setup' );
1272 static $tc = FALSE;
1273 # the % is needed to support urlencoded titles as well
1274 if ( !$tc ) { $tc = Title::legalChars() . '#%'; }
1275
1276 $sk =& $this->mOptions->getSkin();
1277
1278 #split the entire text string on occurences of [[
1279 $a = explode( '[[', ' ' . $s );
1280 #get the first element (all text up to first [[), and remove the space we added
1281 $s = array_shift( $a );
1282 $s = substr( $s, 1 );
1283
1284 # Match a link having the form [[namespace:link|alternate]]trail
1285 static $e1 = FALSE;
1286 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1287 # Match cases where there is no "]]", which might still be images
1288 static $e1_img = FALSE;
1289 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1290 # Match the end of a line for a word that's not followed by whitespace,
1291 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1292 $e2 = wfMsgForContent( 'linkprefix' );
1293
1294 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1295
1296 if( is_null( $this->mTitle ) ) {
1297 wfDebugDieBacktrace( 'nooo' );
1298 }
1299 $nottalk = !$this->mTitle->isTalkPage();
1300
1301 if ( $useLinkPrefixExtension ) {
1302 if ( preg_match( $e2, $s, $m ) ) {
1303 $first_prefix = $m[2];
1304 } else {
1305 $first_prefix = false;
1306 }
1307 } else {
1308 $prefix = '';
1309 }
1310
1311 $selflink = $this->mTitle->getPrefixedText();
1312 wfProfileOut( $fname.'-setup' );
1313
1314 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1315 $useSubpages = $this->areSubpagesAllowed();
1316
1317 # Loop for each link
1318 for ($k = 0; isset( $a[$k] ); $k++) {
1319 $line = $a[$k];
1320 if ( $useLinkPrefixExtension ) {
1321 wfProfileIn( $fname.'-prefixhandling' );
1322 if ( preg_match( $e2, $s, $m ) ) {
1323 $prefix = $m[2];
1324 $s = $m[1];
1325 } else {
1326 $prefix='';
1327 }
1328 # first link
1329 if($first_prefix) {
1330 $prefix = $first_prefix;
1331 $first_prefix = false;
1332 }
1333 wfProfileOut( $fname.'-prefixhandling' );
1334 }
1335
1336 $might_be_img = false;
1337
1338 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1339 $text = $m[2];
1340 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1341 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1342 # the real problem is with the $e1 regex
1343 # See bug 1300.
1344 #
1345 # Still some problems for cases where the ] is meant to be outside punctuation,
1346 # and no image is in sight. See bug 2095.
1347 #
1348 if( $text !== '' && preg_match( "/^\](.*)/s", $m[3], $n ) ) {
1349 $text .= ']'; # so that replaceExternalLinks($text) works later
1350 $m[3] = $n[1];
1351 }
1352 # fix up urlencoded title texts
1353 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1354 $trail = $m[3];
1355 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1356 $might_be_img = true;
1357 $text = $m[2];
1358 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1359 $trail = "";
1360 } else { # Invalid form; output directly
1361 $s .= $prefix . '[[' . $line ;
1362 continue;
1363 }
1364
1365 # Don't allow internal links to pages containing
1366 # PROTO: where PROTO is a valid URL protocol; these
1367 # should be external links.
1368 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1369 $s .= $prefix . '[[' . $line ;
1370 continue;
1371 }
1372
1373 # Make subpage if necessary
1374 if( $useSubpages ) {
1375 $link = $this->maybeDoSubpageLink( $m[1], $text );
1376 } else {
1377 $link = $m[1];
1378 }
1379
1380 $noforce = (substr($m[1], 0, 1) != ':');
1381 if (!$noforce) {
1382 # Strip off leading ':'
1383 $link = substr($link, 1);
1384 }
1385
1386 $nt = Title::newFromText( $this->unstripNoWiki($link, $this->mStripState) );
1387 if( !$nt ) {
1388 $s .= $prefix . '[[' . $line;
1389 continue;
1390 }
1391
1392 #check other language variants of the link
1393 #if the article does not exist
1394 if( $checkVariantLink
1395 && $nt->getArticleID() == 0 ) {
1396 $wgContLang->findVariantLink($link, $nt);
1397 }
1398
1399 $ns = $nt->getNamespace();
1400 $iw = $nt->getInterWiki();
1401
1402 if ($might_be_img) { # if this is actually an invalid link
1403 if ($ns == NS_IMAGE && $noforce) { #but might be an image
1404 $found = false;
1405 while (isset ($a[$k+1]) ) {
1406 #look at the next 'line' to see if we can close it there
1407 $spliced = array_splice( $a, $k + 1, 1 );
1408 $next_line = array_shift( $spliced );
1409 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1410 # the first ]] closes the inner link, the second the image
1411 $found = true;
1412 $text .= '[[' . $m[1];
1413 $trail = $m[2];
1414 break;
1415 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1416 #if there's exactly one ]] that's fine, we'll keep looking
1417 $text .= '[[' . $m[0];
1418 } else {
1419 #if $next_line is invalid too, we need look no further
1420 $text .= '[[' . $next_line;
1421 break;
1422 }
1423 }
1424 if ( !$found ) {
1425 # we couldn't find the end of this imageLink, so output it raw
1426 #but don't ignore what might be perfectly normal links in the text we've examined
1427 $text = $this->replaceInternalLinks($text);
1428 $s .= $prefix . '[[' . $link . '|' . $text;
1429 # note: no $trail, because without an end, there *is* no trail
1430 continue;
1431 }
1432 } else { #it's not an image, so output it raw
1433 $s .= $prefix . '[[' . $link . '|' . $text;
1434 # note: no $trail, because without an end, there *is* no trail
1435 continue;
1436 }
1437 }
1438
1439 $wasblank = ( '' == $text );
1440 if( $wasblank ) $text = $link;
1441
1442
1443 # Link not escaped by : , create the various objects
1444 if( $noforce ) {
1445
1446 # Interwikis
1447 if( $iw && $this->mOptions->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1448 $this->mOutput->addLanguageLink( $nt->getFullText() );
1449 $s = rtrim($s . "\n");
1450 $s .= trim($prefix . $trail, "\n") == '' ? '': $prefix . $trail;
1451 continue;
1452 }
1453
1454 if ( $ns == NS_IMAGE ) {
1455 wfProfileIn( "$fname-image" );
1456 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1457 # recursively parse links inside the image caption
1458 # actually, this will parse them in any other parameters, too,
1459 # but it might be hard to fix that, and it doesn't matter ATM
1460 $text = $this->replaceExternalLinks($text);
1461 $text = $this->replaceInternalLinks($text);
1462
1463 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1464 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1465 $this->mOutput->addImage( $nt->getDBkey() );
1466
1467 wfProfileOut( "$fname-image" );
1468 continue;
1469 }
1470 wfProfileOut( "$fname-image" );
1471
1472 }
1473
1474 if ( $ns == NS_CATEGORY ) {
1475 wfProfileIn( "$fname-category" );
1476 $s = rtrim($s . "\n"); # bug 87
1477
1478 if ( $wasblank ) {
1479 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
1480 $sortkey = $this->mTitle->getText();
1481 } else {
1482 $sortkey = $this->mTitle->getPrefixedText();
1483 }
1484 } else {
1485 $sortkey = $text;
1486 }
1487 $sortkey = Sanitizer::decodeCharReferences( $sortkey );
1488 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1489 $this->mOutput->addCategory( $nt->getDBkey(), $sortkey );
1490
1491 /**
1492 * Strip the whitespace Category links produce, see bug 87
1493 * @todo We might want to use trim($tmp, "\n") here.
1494 */
1495 $s .= trim($prefix . $trail, "\n") == '' ? '': $prefix . $trail;
1496
1497 wfProfileOut( "$fname-category" );
1498 continue;
1499 }
1500 }
1501
1502 if( ( $nt->getPrefixedText() === $selflink ) &&
1503 ( $nt->getFragment() === '' ) ) {
1504 # Self-links are handled specially; generally de-link and change to bold.
1505 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1506 continue;
1507 }
1508
1509 # Special and Media are pseudo-namespaces; no pages actually exist in them
1510 if( $ns == NS_MEDIA ) {
1511 $link = $sk->makeMediaLinkObj( $nt, $text );
1512 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1513 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1514 $this->mOutput->addImage( $nt->getDBkey() );
1515 continue;
1516 } elseif( $ns == NS_SPECIAL ) {
1517 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1518 continue;
1519 } elseif( $ns == NS_IMAGE ) {
1520 $img = Image::newFromTitle( $nt );
1521 if( $img->exists() ) {
1522 // Force a blue link if the file exists; may be a remote
1523 // upload on the shared repository, and we want to see its
1524 // auto-generated page.
1525 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1526 continue;
1527 }
1528 }
1529 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1530 }
1531 wfProfileOut( $fname );
1532 return $s;
1533 }
1534
1535 /**
1536 * Make a link placeholder. The text returned can be later resolved to a real link with
1537 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1538 * parsing of interwiki links, and secondly to allow all extistence checks and
1539 * article length checks (for stub links) to be bundled into a single query.
1540 *
1541 */
1542 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1543 if ( ! is_object($nt) ) {
1544 # Fail gracefully
1545 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1546 } else {
1547 # Separate the link trail from the rest of the link
1548 list( $inside, $trail ) = Linker::splitTrail( $trail );
1549
1550 if ( $nt->isExternal() ) {
1551 $nr = array_push( $this->mInterwikiLinkHolders['texts'], $prefix.$text.$inside );
1552 $this->mInterwikiLinkHolders['titles'][] = $nt;
1553 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1554 } else {
1555 $nr = array_push( $this->mLinkHolders['namespaces'], $nt->getNamespace() );
1556 $this->mLinkHolders['dbkeys'][] = $nt->getDBkey();
1557 $this->mLinkHolders['queries'][] = $query;
1558 $this->mLinkHolders['texts'][] = $prefix.$text.$inside;
1559 $this->mLinkHolders['titles'][] = $nt;
1560
1561 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1562 }
1563 }
1564 return $retVal;
1565 }
1566
1567 /**
1568 * Render a forced-blue link inline; protect against double expansion of
1569 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1570 * Since this little disaster has to split off the trail text to avoid
1571 * breaking URLs in the following text without breaking trails on the
1572 * wiki links, it's been made into a horrible function.
1573 *
1574 * @param Title $nt
1575 * @param string $text
1576 * @param string $query
1577 * @param string $trail
1578 * @param string $prefix
1579 * @return string HTML-wikitext mix oh yuck
1580 */
1581 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1582 list( $inside, $trail ) = Linker::splitTrail( $trail );
1583 $sk =& $this->mOptions->getSkin();
1584 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1585 return $this->armorLinks( $link ) . $trail;
1586 }
1587
1588 /**
1589 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1590 * going to go through further parsing steps before inline URL expansion.
1591 *
1592 * In particular this is important when using action=render, which causes
1593 * full URLs to be included.
1594 *
1595 * Oh man I hate our multi-layer parser!
1596 *
1597 * @param string more-or-less HTML
1598 * @return string less-or-more HTML with NOPARSE bits
1599 */
1600 function armorLinks( $text ) {
1601 return preg_replace( "/\b(" . wfUrlProtocols() . ')/',
1602 "{$this->mUniqPrefix}NOPARSE$1", $text );
1603 }
1604
1605 /**
1606 * Return true if subpage links should be expanded on this page.
1607 * @return bool
1608 */
1609 function areSubpagesAllowed() {
1610 # Some namespaces don't allow subpages
1611 global $wgNamespacesWithSubpages;
1612 return !empty($wgNamespacesWithSubpages[$this->mTitle->getNamespace()]);
1613 }
1614
1615 /**
1616 * Handle link to subpage if necessary
1617 * @param string $target the source of the link
1618 * @param string &$text the link text, modified as necessary
1619 * @return string the full name of the link
1620 * @access private
1621 */
1622 function maybeDoSubpageLink($target, &$text) {
1623 # Valid link forms:
1624 # Foobar -- normal
1625 # :Foobar -- override special treatment of prefix (images, language links)
1626 # /Foobar -- convert to CurrentPage/Foobar
1627 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1628 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1629 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1630
1631 $fname = 'Parser::maybeDoSubpageLink';
1632 wfProfileIn( $fname );
1633 $ret = $target; # default return value is no change
1634
1635 # Some namespaces don't allow subpages,
1636 # so only perform processing if subpages are allowed
1637 if( $this->areSubpagesAllowed() ) {
1638 # Look at the first character
1639 if( $target != '' && $target{0} == '/' ) {
1640 # / at end means we don't want the slash to be shown
1641 if( substr( $target, -1, 1 ) == '/' ) {
1642 $target = substr( $target, 1, -1 );
1643 $noslash = $target;
1644 } else {
1645 $noslash = substr( $target, 1 );
1646 }
1647
1648 $ret = $this->mTitle->getPrefixedText(). '/' . trim($noslash);
1649 if( '' === $text ) {
1650 $text = $target;
1651 } # this might be changed for ugliness reasons
1652 } else {
1653 # check for .. subpage backlinks
1654 $dotdotcount = 0;
1655 $nodotdot = $target;
1656 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1657 ++$dotdotcount;
1658 $nodotdot = substr( $nodotdot, 3 );
1659 }
1660 if($dotdotcount > 0) {
1661 $exploded = explode( '/', $this->mTitle->GetPrefixedText() );
1662 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1663 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1664 # / at the end means don't show full path
1665 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1666 $nodotdot = substr( $nodotdot, 0, -1 );
1667 if( '' === $text ) {
1668 $text = $nodotdot;
1669 }
1670 }
1671 $nodotdot = trim( $nodotdot );
1672 if( $nodotdot != '' ) {
1673 $ret .= '/' . $nodotdot;
1674 }
1675 }
1676 }
1677 }
1678 }
1679
1680 wfProfileOut( $fname );
1681 return $ret;
1682 }
1683
1684 /**#@+
1685 * Used by doBlockLevels()
1686 * @access private
1687 */
1688 /* private */ function closeParagraph() {
1689 $result = '';
1690 if ( '' != $this->mLastSection ) {
1691 $result = '</' . $this->mLastSection . ">\n";
1692 }
1693 $this->mInPre = false;
1694 $this->mLastSection = '';
1695 return $result;
1696 }
1697 # getCommon() returns the length of the longest common substring
1698 # of both arguments, starting at the beginning of both.
1699 #
1700 /* private */ function getCommon( $st1, $st2 ) {
1701 $fl = strlen( $st1 );
1702 $shorter = strlen( $st2 );
1703 if ( $fl < $shorter ) { $shorter = $fl; }
1704
1705 for ( $i = 0; $i < $shorter; ++$i ) {
1706 if ( $st1{$i} != $st2{$i} ) { break; }
1707 }
1708 return $i;
1709 }
1710 # These next three functions open, continue, and close the list
1711 # element appropriate to the prefix character passed into them.
1712 #
1713 /* private */ function openList( $char ) {
1714 $result = $this->closeParagraph();
1715
1716 if ( '*' == $char ) { $result .= '<ul><li>'; }
1717 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1718 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1719 else if ( ';' == $char ) {
1720 $result .= '<dl><dt>';
1721 $this->mDTopen = true;
1722 }
1723 else { $result = '<!-- ERR 1 -->'; }
1724
1725 return $result;
1726 }
1727
1728 /* private */ function nextItem( $char ) {
1729 if ( '*' == $char || '#' == $char ) { return '</li><li>'; }
1730 else if ( ':' == $char || ';' == $char ) {
1731 $close = '</dd>';
1732 if ( $this->mDTopen ) { $close = '</dt>'; }
1733 if ( ';' == $char ) {
1734 $this->mDTopen = true;
1735 return $close . '<dt>';
1736 } else {
1737 $this->mDTopen = false;
1738 return $close . '<dd>';
1739 }
1740 }
1741 return '<!-- ERR 2 -->';
1742 }
1743
1744 /* private */ function closeList( $char ) {
1745 if ( '*' == $char ) { $text = '</li></ul>'; }
1746 else if ( '#' == $char ) { $text = '</li></ol>'; }
1747 else if ( ':' == $char ) {
1748 if ( $this->mDTopen ) {
1749 $this->mDTopen = false;
1750 $text = '</dt></dl>';
1751 } else {
1752 $text = '</dd></dl>';
1753 }
1754 }
1755 else { return '<!-- ERR 3 -->'; }
1756 return $text."\n";
1757 }
1758 /**#@-*/
1759
1760 /**
1761 * Make lists from lines starting with ':', '*', '#', etc.
1762 *
1763 * @access private
1764 * @return string the lists rendered as HTML
1765 */
1766 function doBlockLevels( $text, $linestart ) {
1767 $fname = 'Parser::doBlockLevels';
1768 wfProfileIn( $fname );
1769
1770 # Parsing through the text line by line. The main thing
1771 # happening here is handling of block-level elements p, pre,
1772 # and making lists from lines starting with * # : etc.
1773 #
1774 $textLines = explode( "\n", $text );
1775
1776 $lastPrefix = $output = '';
1777 $this->mDTopen = $inBlockElem = false;
1778 $prefixLength = 0;
1779 $paragraphStack = false;
1780
1781 if ( !$linestart ) {
1782 $output .= array_shift( $textLines );
1783 }
1784 foreach ( $textLines as $oLine ) {
1785 $lastPrefixLength = strlen( $lastPrefix );
1786 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1787 $preOpenMatch = preg_match('/<pre/i', $oLine );
1788 if ( !$this->mInPre ) {
1789 # Multiple prefixes may abut each other for nested lists.
1790 $prefixLength = strspn( $oLine, '*#:;' );
1791 $pref = substr( $oLine, 0, $prefixLength );
1792
1793 # eh?
1794 $pref2 = str_replace( ';', ':', $pref );
1795 $t = substr( $oLine, $prefixLength );
1796 $this->mInPre = !empty($preOpenMatch);
1797 } else {
1798 # Don't interpret any other prefixes in preformatted text
1799 $prefixLength = 0;
1800 $pref = $pref2 = '';
1801 $t = $oLine;
1802 }
1803
1804 # List generation
1805 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1806 # Same as the last item, so no need to deal with nesting or opening stuff
1807 $output .= $this->nextItem( substr( $pref, -1 ) );
1808 $paragraphStack = false;
1809
1810 if ( substr( $pref, -1 ) == ';') {
1811 # The one nasty exception: definition lists work like this:
1812 # ; title : definition text
1813 # So we check for : in the remainder text to split up the
1814 # title and definition, without b0rking links.
1815 $term = $t2 = '';
1816 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1817 $t = $t2;
1818 $output .= $term . $this->nextItem( ':' );
1819 }
1820 }
1821 } elseif( $prefixLength || $lastPrefixLength ) {
1822 # Either open or close a level...
1823 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1824 $paragraphStack = false;
1825
1826 while( $commonPrefixLength < $lastPrefixLength ) {
1827 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1828 --$lastPrefixLength;
1829 }
1830 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1831 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1832 }
1833 while ( $prefixLength > $commonPrefixLength ) {
1834 $char = substr( $pref, $commonPrefixLength, 1 );
1835 $output .= $this->openList( $char );
1836
1837 if ( ';' == $char ) {
1838 # FIXME: This is dupe of code above
1839 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1840 $t = $t2;
1841 $output .= $term . $this->nextItem( ':' );
1842 }
1843 }
1844 ++$commonPrefixLength;
1845 }
1846 $lastPrefix = $pref2;
1847 }
1848 if( 0 == $prefixLength ) {
1849 wfProfileIn( "$fname-paragraph" );
1850 # No prefix (not in list)--go to paragraph mode
1851 // XXX: use a stack for nestable elements like span, table and div
1852 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1853 $closematch = preg_match(
1854 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1855 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix.'-pre|<\\/li|<\\/ul)/iS', $t );
1856 if ( $openmatch or $closematch ) {
1857 $paragraphStack = false;
1858 $output .= $this->closeParagraph();
1859 if ( $preOpenMatch and !$preCloseMatch ) {
1860 $this->mInPre = true;
1861 }
1862 if ( $closematch ) {
1863 $inBlockElem = false;
1864 } else {
1865 $inBlockElem = true;
1866 }
1867 } else if ( !$inBlockElem && !$this->mInPre ) {
1868 if ( ' ' == $t{0} and ( $this->mLastSection == 'pre' or trim($t) != '' ) ) {
1869 // pre
1870 if ($this->mLastSection != 'pre') {
1871 $paragraphStack = false;
1872 $output .= $this->closeParagraph().'<pre>';
1873 $this->mLastSection = 'pre';
1874 }
1875 $t = substr( $t, 1 );
1876 } else {
1877 // paragraph
1878 if ( '' == trim($t) ) {
1879 if ( $paragraphStack ) {
1880 $output .= $paragraphStack.'<br />';
1881 $paragraphStack = false;
1882 $this->mLastSection = 'p';
1883 } else {
1884 if ($this->mLastSection != 'p' ) {
1885 $output .= $this->closeParagraph();
1886 $this->mLastSection = '';
1887 $paragraphStack = '<p>';
1888 } else {
1889 $paragraphStack = '</p><p>';
1890 }
1891 }
1892 } else {
1893 if ( $paragraphStack ) {
1894 $output .= $paragraphStack;
1895 $paragraphStack = false;
1896 $this->mLastSection = 'p';
1897 } else if ($this->mLastSection != 'p') {
1898 $output .= $this->closeParagraph().'<p>';
1899 $this->mLastSection = 'p';
1900 }
1901 }
1902 }
1903 }
1904 wfProfileOut( "$fname-paragraph" );
1905 }
1906 // somewhere above we forget to get out of pre block (bug 785)
1907 if($preCloseMatch && $this->mInPre) {
1908 $this->mInPre = false;
1909 }
1910 if ($paragraphStack === false) {
1911 $output .= $t."\n";
1912 }
1913 }
1914 while ( $prefixLength ) {
1915 $output .= $this->closeList( $pref2{$prefixLength-1} );
1916 --$prefixLength;
1917 }
1918 if ( '' != $this->mLastSection ) {
1919 $output .= '</' . $this->mLastSection . '>';
1920 $this->mLastSection = '';
1921 }
1922
1923 wfProfileOut( $fname );
1924 return $output;
1925 }
1926
1927 /**
1928 * Split up a string on ':', ignoring any occurences inside
1929 * <a>..</a> or <span>...</span>
1930 * @param string $str the string to split
1931 * @param string &$before set to everything before the ':'
1932 * @param string &$after set to everything after the ':'
1933 * return string the position of the ':', or false if none found
1934 */
1935 function findColonNoLinks($str, &$before, &$after) {
1936 # I wonder if we should make this count all tags, not just <a>
1937 # and <span>. That would prevent us from matching a ':' that
1938 # comes in the middle of italics other such formatting....
1939 # -- Wil
1940 $fname = 'Parser::findColonNoLinks';
1941 wfProfileIn( $fname );
1942 $pos = 0;
1943 do {
1944 $colon = strpos($str, ':', $pos);
1945
1946 if ($colon !== false) {
1947 $before = substr($str, 0, $colon);
1948 $after = substr($str, $colon + 1);
1949
1950 # Skip any ':' within <a> or <span> pairs
1951 $a = substr_count($before, '<a');
1952 $s = substr_count($before, '<span');
1953 $ca = substr_count($before, '</a>');
1954 $cs = substr_count($before, '</span>');
1955
1956 if ($a <= $ca and $s <= $cs) {
1957 # Tags are balanced before ':'; ok
1958 break;
1959 }
1960 $pos = $colon + 1;
1961 }
1962 } while ($colon !== false);
1963 wfProfileOut( $fname );
1964 return $colon;
1965 }
1966
1967 /**
1968 * Return value of a magic variable (like PAGENAME)
1969 *
1970 * @access private
1971 */
1972 function getVariableValue( $index ) {
1973 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
1974
1975 /**
1976 * Some of these require message or data lookups and can be
1977 * expensive to check many times.
1978 */
1979 static $varCache = array();
1980 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) )
1981 if ( isset( $varCache[$index] ) )
1982 return $varCache[$index];
1983
1984 $ts = time();
1985 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
1986
1987 switch ( $index ) {
1988 case MAG_CURRENTMONTH:
1989 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
1990 case MAG_CURRENTMONTHNAME:
1991 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
1992 case MAG_CURRENTMONTHNAMEGEN:
1993 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
1994 case MAG_CURRENTMONTHABBREV:
1995 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
1996 case MAG_CURRENTDAY:
1997 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
1998 case MAG_CURRENTDAY2:
1999 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2000 case MAG_PAGENAME:
2001 return $this->mTitle->getText();
2002 case MAG_PAGENAMEE:
2003 return $this->mTitle->getPartialURL();
2004 case MAG_FULLPAGENAME:
2005 return $this->mTitle->getPrefixedText();
2006 case MAG_FULLPAGENAMEE:
2007 return $this->mTitle->getPrefixedURL();
2008 case MAG_REVISIONID:
2009 return $this->mRevisionId;
2010 case MAG_NAMESPACE:
2011 return $wgContLang->getNsText( $this->mTitle->getNamespace() );
2012 case MAG_NAMESPACEE:
2013 return wfUrlencode( $wgContLang->getNsText( $this->mTitle->getNamespace() ) );
2014 case MAG_CURRENTDAYNAME:
2015 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) + 1 );
2016 case MAG_CURRENTYEAR:
2017 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2018 case MAG_CURRENTTIME:
2019 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW, $ts ), false, false );
2020 case MAG_CURRENTWEEK:
2021 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2022 // int to remove the padding
2023 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2024 case MAG_CURRENTDOW:
2025 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2026 case MAG_NUMBEROFARTICLES:
2027 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
2028 case MAG_NUMBEROFFILES:
2029 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
2030 case MAG_SITENAME:
2031 return $wgSitename;
2032 case MAG_SERVER:
2033 return $wgServer;
2034 case MAG_SERVERNAME:
2035 return $wgServerName;
2036 case MAG_SCRIPTPATH:
2037 return $wgScriptPath;
2038 default:
2039 $ret = null;
2040 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2041 return $ret;
2042 else
2043 return null;
2044 }
2045 }
2046
2047 /**
2048 * initialise the magic variables (like CURRENTMONTHNAME)
2049 *
2050 * @access private
2051 */
2052 function initialiseVariables() {
2053 $fname = 'Parser::initialiseVariables';
2054 wfProfileIn( $fname );
2055 global $wgVariableIDs;
2056 $this->mVariables = array();
2057 foreach ( $wgVariableIDs as $id ) {
2058 $mw =& MagicWord::get( $id );
2059 $mw->addToArray( $this->mVariables, $id );
2060 }
2061 wfProfileOut( $fname );
2062 }
2063
2064 /**
2065 * parse any parentheses in format ((title|part|part))
2066 * and call callbacks to get a replacement text for any found piece
2067 *
2068 * @param string $text The text to parse
2069 * @param array $callbacks rules in form:
2070 * '{' => array( # opening parentheses
2071 * 'end' => '}', # closing parentheses
2072 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2073 * 4 => callback # replacement callback to call if {{{{..}}}} is found
2074 * )
2075 * )
2076 * @access private
2077 */
2078 function replace_callback ($text, $callbacks) {
2079 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2080 $lastOpeningBrace = -1; # last not closed parentheses
2081
2082 for ($i = 0; $i < strlen($text); $i++) {
2083 # check for any opening brace
2084 $rule = null;
2085 $nextPos = -1;
2086 foreach ($callbacks as $key => $value) {
2087 $pos = strpos ($text, $key, $i);
2088 if (false !== $pos && (-1 == $nextPos || $pos < $nextPos)) {
2089 $rule = $value;
2090 $nextPos = $pos;
2091 }
2092 }
2093
2094 if ($lastOpeningBrace >= 0) {
2095 $pos = strpos ($text, $openingBraceStack[$lastOpeningBrace]['braceEnd'], $i);
2096
2097 if (false !== $pos && (-1 == $nextPos || $pos < $nextPos)){
2098 $rule = null;
2099 $nextPos = $pos;
2100 }
2101
2102 $pos = strpos ($text, '|', $i);
2103
2104 if (false !== $pos && (-1 == $nextPos || $pos < $nextPos)){
2105 $rule = null;
2106 $nextPos = $pos;
2107 }
2108 }
2109
2110 if ($nextPos == -1)
2111 break;
2112
2113 $i = $nextPos;
2114
2115 # found openning brace, lets add it to parentheses stack
2116 if (null != $rule) {
2117 $piece = array('brace' => $text[$i],
2118 'braceEnd' => $rule['end'],
2119 'count' => 1,
2120 'title' => '',
2121 'parts' => null);
2122
2123 # count openning brace characters
2124 while ($i+1 < strlen($text) && $text[$i+1] == $piece['brace']) {
2125 $piece['count']++;
2126 $i++;
2127 }
2128
2129 $piece['startAt'] = $i+1;
2130 $piece['partStart'] = $i+1;
2131
2132 # we need to add to stack only if openning brace count is enough for any given rule
2133 foreach ($rule['cb'] as $cnt => $fn) {
2134 if ($piece['count'] >= $cnt) {
2135 $lastOpeningBrace ++;
2136 $openingBraceStack[$lastOpeningBrace] = $piece;
2137 break;
2138 }
2139 }
2140
2141 continue;
2142 }
2143 else if ($lastOpeningBrace >= 0) {
2144 # first check if it is a closing brace
2145 if ($openingBraceStack[$lastOpeningBrace]['braceEnd'] == $text[$i]) {
2146 # lets check if it is enough characters for closing brace
2147 $count = 1;
2148 while ($i+$count < strlen($text) && $text[$i+$count] == $text[$i])
2149 $count++;
2150
2151 # if there are more closing parentheses than opening ones, we parse less
2152 if ($openingBraceStack[$lastOpeningBrace]['count'] < $count)
2153 $count = $openingBraceStack[$lastOpeningBrace]['count'];
2154
2155 # check for maximum matching characters (if there are 5 closing characters, we will probably need only 3 - depending on the rules)
2156 $matchingCount = 0;
2157 $matchingCallback = null;
2158 foreach ($callbacks[$openingBraceStack[$lastOpeningBrace]['brace']]['cb'] as $cnt => $fn) {
2159 if ($count >= $cnt && $matchingCount < $cnt) {
2160 $matchingCount = $cnt;
2161 $matchingCallback = $fn;
2162 }
2163 }
2164
2165 if ($matchingCount == 0) {
2166 $i += $count - 1;
2167 continue;
2168 }
2169
2170 # lets set a title or last part (if '|' was found)
2171 if (null === $openingBraceStack[$lastOpeningBrace]['parts'])
2172 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2173 else
2174 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2175
2176 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2177 $pieceEnd = $i + $matchingCount;
2178
2179 if( is_callable( $matchingCallback ) ) {
2180 $cbArgs = array (
2181 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2182 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2183 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2184 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == '\n')),
2185 );
2186 # finally we can call a user callback and replace piece of text
2187 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2188 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2189 $i = $pieceStart + strlen($replaceWith) - 1;
2190 }
2191 else {
2192 # null value for callback means that parentheses should be parsed, but not replaced
2193 $i += $matchingCount - 1;
2194 }
2195
2196 # reset last openning parentheses, but keep it in case there are unused characters
2197 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2198 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2199 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2200 'title' => '',
2201 'parts' => null,
2202 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2203 $openingBraceStack[$lastOpeningBrace--] = null;
2204
2205 if ($matchingCount < $piece['count']) {
2206 $piece['count'] -= $matchingCount;
2207 $piece['startAt'] -= $matchingCount;
2208 $piece['partStart'] = $piece['startAt'];
2209 # do we still qualify for any callback with remaining count?
2210 foreach ($callbacks[$piece['brace']]['cb'] as $cnt => $fn) {
2211 if ($piece['count'] >= $cnt) {
2212 $lastOpeningBrace ++;
2213 $openingBraceStack[$lastOpeningBrace] = $piece;
2214 break;
2215 }
2216 }
2217 }
2218 continue;
2219 }
2220
2221 # lets set a title if it is a first separator, or next part otherwise
2222 if ($text[$i] == '|') {
2223 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2224 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2225 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2226 }
2227 else
2228 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2229
2230 $openingBraceStack[$lastOpeningBrace]['partStart'] = $i + 1;
2231 }
2232 }
2233 }
2234
2235 return $text;
2236 }
2237
2238 /**
2239 * Replace magic variables, templates, and template arguments
2240 * with the appropriate text. Templates are substituted recursively,
2241 * taking care to avoid infinite loops.
2242 *
2243 * Note that the substitution depends on value of $mOutputType:
2244 * OT_WIKI: only {{subst:}} templates
2245 * OT_MSG: only magic variables
2246 * OT_HTML: all templates and magic variables
2247 *
2248 * @param string $tex The text to transform
2249 * @param array $args Key-value pairs representing template parameters to substitute
2250 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2251 * @access private
2252 */
2253 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2254 # Prevent too big inclusions
2255 if( strlen( $text ) > MAX_INCLUDE_SIZE ) {
2256 return $text;
2257 }
2258
2259 $fname = 'Parser::replaceVariables';
2260 wfProfileIn( $fname );
2261
2262 # This function is called recursively. To keep track of arguments we need a stack:
2263 array_push( $this->mArgStack, $args );
2264
2265 $braceCallbacks = array();
2266 if ( !$argsOnly ) {
2267 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2268 }
2269 if ( $this->mOutputType == OT_HTML || $this->mOutputType == OT_WIKI ) {
2270 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2271 }
2272 $callbacks = array();
2273 $callbacks['{'] = array('end' => '}', 'cb' => $braceCallbacks);
2274 $callbacks['['] = array('end' => ']', 'cb' => array(2=>null));
2275 $text = $this->replace_callback ($text, $callbacks);
2276
2277 array_pop( $this->mArgStack );
2278
2279 wfProfileOut( $fname );
2280 return $text;
2281 }
2282
2283 /**
2284 * Replace magic variables
2285 * @access private
2286 */
2287 function variableSubstitution( $matches ) {
2288 $fname = 'Parser::variableSubstitution';
2289 $varname = $matches[1];
2290 wfProfileIn( $fname );
2291 if ( !$this->mVariables ) {
2292 $this->initialiseVariables();
2293 }
2294 $skip = false;
2295 if ( $this->mOutputType == OT_WIKI ) {
2296 # Do only magic variables prefixed by SUBST
2297 $mwSubst =& MagicWord::get( MAG_SUBST );
2298 if (!$mwSubst->matchStartAndRemove( $varname ))
2299 $skip = true;
2300 # Note that if we don't substitute the variable below,
2301 # we don't remove the {{subst:}} magic word, in case
2302 # it is a template rather than a magic variable.
2303 }
2304 if ( !$skip && array_key_exists( $varname, $this->mVariables ) ) {
2305 $id = $this->mVariables[$varname];
2306 $text = $this->getVariableValue( $id );
2307 $this->mOutput->mContainsOldMagic = true;
2308 } else {
2309 $text = $matches[0];
2310 }
2311 wfProfileOut( $fname );
2312 return $text;
2313 }
2314
2315 # Split template arguments
2316 function getTemplateArgs( $argsString ) {
2317 if ( $argsString === '' ) {
2318 return array();
2319 }
2320
2321 $args = explode( '|', substr( $argsString, 1 ) );
2322
2323 # If any of the arguments contains a '[[' but no ']]', it needs to be
2324 # merged with the next arg because the '|' character between belongs
2325 # to the link syntax and not the template parameter syntax.
2326 $argc = count($args);
2327
2328 for ( $i = 0; $i < $argc-1; $i++ ) {
2329 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2330 $args[$i] .= '|'.$args[$i+1];
2331 array_splice($args, $i+1, 1);
2332 $i--;
2333 $argc--;
2334 }
2335 }
2336
2337 return $args;
2338 }
2339
2340 /**
2341 * Return the text of a template, after recursively
2342 * replacing any variables or templates within the template.
2343 *
2344 * @param array $piece The parts of the template
2345 * $piece['text']: matched text
2346 * $piece['title']: the title, i.e. the part before the |
2347 * $piece['parts']: the parameter array
2348 * @return string the text of the template
2349 * @access private
2350 */
2351 function braceSubstitution( $piece ) {
2352 global $wgContLang;
2353 $fname = 'Parser::braceSubstitution';
2354 wfProfileIn( $fname );
2355
2356 # Flags
2357 $found = false; # $text has been filled
2358 $nowiki = false; # wiki markup in $text should be escaped
2359 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2360 $noargs = false; # Don't replace triple-brace arguments in $text
2361 $replaceHeadings = false; # Make the edit section links go to the template not the article
2362 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2363 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2364
2365 # Title object, where $text came from
2366 $title = NULL;
2367
2368 $linestart = '';
2369
2370 # $part1 is the bit before the first |, and must contain only title characters
2371 # $args is a list of arguments, starting from index 0, not including $part1
2372
2373 $part1 = $piece['title'];
2374 # If the third subpattern matched anything, it will start with |
2375
2376 if (null == $piece['parts']) {
2377 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2378 if ($replaceWith != $piece['text']) {
2379 $text = $replaceWith;
2380 $found = true;
2381 $noparse = true;
2382 $noargs = true;
2383 }
2384 }
2385
2386 $args = (null == $piece['parts']) ? array() : $piece['parts'];
2387 $argc = count( $args );
2388
2389 # SUBST
2390 if ( !$found ) {
2391 $mwSubst =& MagicWord::get( MAG_SUBST );
2392 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType == OT_WIKI) ) {
2393 # One of two possibilities is true:
2394 # 1) Found SUBST but not in the PST phase
2395 # 2) Didn't find SUBST and in the PST phase
2396 # In either case, return without further processing
2397 $text = $piece['text'];
2398 $found = true;
2399 $noparse = true;
2400 $noargs = true;
2401 }
2402 }
2403
2404 # MSG, MSGNW, INT and RAW
2405 if ( !$found ) {
2406 # Check for MSGNW:
2407 $mwMsgnw =& MagicWord::get( MAG_MSGNW );
2408 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2409 $nowiki = true;
2410 } else {
2411 # Remove obsolete MSG:
2412 $mwMsg =& MagicWord::get( MAG_MSG );
2413 $mwMsg->matchStartAndRemove( $part1 );
2414 }
2415
2416 # Check for RAW:
2417 $mwRaw =& MagicWord::get( MAG_RAW );
2418 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2419 $forceRawInterwiki = true;
2420 }
2421
2422 # Check if it is an internal message
2423 $mwInt =& MagicWord::get( MAG_INT );
2424 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2425 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2426 $text = $linestart . wfMsgReal( $part1, $args, true );
2427 $found = true;
2428 }
2429 }
2430 }
2431
2432 # NS
2433 if ( !$found ) {
2434 # Check for NS: (namespace expansion)
2435 $mwNs = MagicWord::get( MAG_NS );
2436 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2437 if ( intval( $part1 ) || $part1 == "0" ) {
2438 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2439 $found = true;
2440 } else {
2441 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2442 if ( !is_null( $index ) ) {
2443 $text = $linestart . $wgContLang->getNsText( $index );
2444 $found = true;
2445 }
2446 }
2447 }
2448 }
2449
2450 # LCFIRST, UCFIRST, LC and UC
2451 if ( !$found ) {
2452 $lcfirst =& MagicWord::get( MAG_LCFIRST );
2453 $ucfirst =& MagicWord::get( MAG_UCFIRST );
2454 $lc =& MagicWord::get( MAG_LC );
2455 $uc =& MagicWord::get( MAG_UC );
2456 if ( $lcfirst->matchStartAndRemove( $part1 ) ) {
2457 $text = $linestart . $wgContLang->lcfirst( $part1 );
2458 $found = true;
2459 } else if ( $ucfirst->matchStartAndRemove( $part1 ) ) {
2460 $text = $linestart . $wgContLang->ucfirst( $part1 );
2461 $found = true;
2462 } else if ( $lc->matchStartAndRemove( $part1 ) ) {
2463 $text = $linestart . $wgContLang->lc( $part1 );
2464 $found = true;
2465 } else if ( $uc->matchStartAndRemove( $part1 ) ) {
2466 $text = $linestart . $wgContLang->uc( $part1 );
2467 $found = true;
2468 }
2469 }
2470
2471 # LOCALURL and FULLURL
2472 if ( !$found ) {
2473 $mwLocal =& MagicWord::get( MAG_LOCALURL );
2474 $mwLocalE =& MagicWord::get( MAG_LOCALURLE );
2475 $mwFull =& MagicWord::get( MAG_FULLURL );
2476 $mwFullE =& MagicWord::get( MAG_FULLURLE );
2477
2478
2479 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2480 $func = 'getLocalURL';
2481 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2482 $func = 'escapeLocalURL';
2483 } elseif ( $mwFull->matchStartAndRemove( $part1 ) ) {
2484 $func = 'getFullURL';
2485 } elseif ( $mwFullE->matchStartAndRemove( $part1 ) ) {
2486 $func = 'escapeFullURL';
2487 } else {
2488 $func = false;
2489 }
2490
2491 if ( $func !== false ) {
2492 $title = Title::newFromText( $part1 );
2493 if ( !is_null( $title ) ) {
2494 if ( $argc > 0 ) {
2495 $text = $linestart . $title->$func( $args[0] );
2496 } else {
2497 $text = $linestart . $title->$func();
2498 }
2499 $found = true;
2500 }
2501 }
2502 }
2503
2504 # GRAMMAR
2505 if ( !$found && $argc == 1 ) {
2506 $mwGrammar =& MagicWord::get( MAG_GRAMMAR );
2507 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2508 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
2509 $found = true;
2510 }
2511 }
2512
2513 # PLURAL
2514 if ( !$found && $argc >= 2 ) {
2515 $mwPluralForm =& MagicWord::get( MAG_PLURAL );
2516 if ( $mwPluralForm->matchStartAndRemove( $part1 ) ) {
2517 if ($argc==2) {$args[2]=$args[1];}
2518 $text = $linestart . $wgContLang->convertPlural( $part1, $args[0], $args[1], $args[2]);
2519 $found = true;
2520 }
2521 }
2522
2523 # Template table test
2524
2525 # Did we encounter this template already? If yes, it is in the cache
2526 # and we need to check for loops.
2527 if ( !$found && isset( $this->mTemplates[$piece['title']] ) ) {
2528 $found = true;
2529
2530 # Infinite loop test
2531 if ( isset( $this->mTemplatePath[$part1] ) ) {
2532 $noparse = true;
2533 $noargs = true;
2534 $found = true;
2535 $text = $linestart .
2536 '{{' . $part1 . '}}' .
2537 '<!-- WARNING: template loop detected -->';
2538 wfDebug( "$fname: template loop broken at '$part1'\n" );
2539 } else {
2540 # set $text to cached message.
2541 $text = $linestart . $this->mTemplates[$piece['title']];
2542 }
2543 }
2544
2545 # Load from database
2546 $lastPathLevel = $this->mTemplatePath;
2547 if ( !$found ) {
2548 $ns = NS_TEMPLATE;
2549 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
2550 if ($subpage !== '') {
2551 $ns = $this->mTitle->getNamespace();
2552 }
2553 $title = Title::newFromText( $part1, $ns );
2554
2555 if ( !is_null( $title ) ) {
2556 if ( !$title->isExternal() ) {
2557 # Check for excessive inclusion
2558 $dbk = $title->getPrefixedDBkey();
2559 if ( $this->incrementIncludeCount( $dbk ) ) {
2560 if ( $title->getNamespace() == NS_SPECIAL && $this->mOptions->getAllowSpecialInclusion() ) {
2561 # Capture special page output
2562 $text = SpecialPage::capturePath( $title );
2563 if ( is_string( $text ) ) {
2564 $found = true;
2565 $noparse = true;
2566 $noargs = true;
2567 $isHTML = true;
2568 $this->disableCache();
2569 }
2570 } else {
2571 $articleContent = $this->fetchTemplate( $title );
2572 if ( $articleContent !== false ) {
2573 $found = true;
2574 $text = $articleContent;
2575 $replaceHeadings = true;
2576 }
2577 }
2578 }
2579
2580 # If the title is valid but undisplayable, make a link to it
2581 if ( $this->mOutputType == OT_HTML && !$found ) {
2582 $text = '[['.$title->getPrefixedText().']]';
2583 $found = true;
2584 }
2585 } elseif ( $title->isTrans() ) {
2586 // Interwiki transclusion
2587 if ( $this->mOutputType == OT_HTML && !$forceRawInterwiki ) {
2588 $text = $this->interwikiTransclude( $title, 'render' );
2589 $isHTML = true;
2590 $noparse = true;
2591 } else {
2592 $text = $this->interwikiTransclude( $title, 'raw' );
2593 $replaceHeadings = true;
2594 }
2595 $found = true;
2596 }
2597
2598 # Template cache array insertion
2599 # Use the original $piece['title'] not the mangled $part1, so that
2600 # modifiers such as RAW: produce separate cache entries
2601 if( $found ) {
2602 $this->mTemplates[$piece['title']] = $text;
2603 $text = $linestart . $text;
2604 }
2605 }
2606 }
2607
2608 # Recursive parsing, escaping and link table handling
2609 # Only for HTML output
2610 if ( $nowiki && $found && $this->mOutputType == OT_HTML ) {
2611 $text = wfEscapeWikiText( $text );
2612 } elseif ( ($this->mOutputType == OT_HTML || $this->mOutputType == OT_WIKI) && $found ) {
2613 if ( !$noargs ) {
2614 # Clean up argument array
2615 $assocArgs = array();
2616 $index = 1;
2617 foreach( $args as $arg ) {
2618 $eqpos = strpos( $arg, '=' );
2619 if ( $eqpos === false ) {
2620 $assocArgs[$index++] = $arg;
2621 } else {
2622 $name = trim( substr( $arg, 0, $eqpos ) );
2623 $value = trim( substr( $arg, $eqpos+1 ) );
2624 if ( $value === false ) {
2625 $value = '';
2626 }
2627 if ( $name !== false ) {
2628 $assocArgs[$name] = $value;
2629 }
2630 }
2631 }
2632
2633 # Add a new element to the templace recursion path
2634 $this->mTemplatePath[$part1] = 1;
2635 }
2636
2637 if ( !$noparse ) {
2638 # If there are any <onlyinclude> tags, only include them
2639 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
2640 preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
2641 $text = '';
2642 foreach ($m[1] as $piece)
2643 $text .= $piece;
2644 }
2645 # Remove <noinclude> sections and <includeonly> tags
2646 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
2647 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
2648
2649 if( $this->mOutputType == OT_HTML ) {
2650 # Strip <nowiki>, <pre>, etc.
2651 $text = $this->strip( $text, $this->mStripState );
2652 $text = Sanitizer::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2653 }
2654 $text = $this->replaceVariables( $text, $assocArgs );
2655
2656 # If the template begins with a table or block-level
2657 # element, it should be treated as beginning a new line.
2658 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2659 $text = "\n" . $text;
2660 }
2661 } elseif ( !$noargs ) {
2662 # $noparse and !$noargs
2663 # Just replace the arguments, not any double-brace items
2664 # This is used for rendered interwiki transclusion
2665 $text = $this->replaceVariables( $text, $assocArgs, true );
2666 }
2667 }
2668 # Prune lower levels off the recursion check path
2669 $this->mTemplatePath = $lastPathLevel;
2670
2671 if ( !$found ) {
2672 wfProfileOut( $fname );
2673 return $piece['text'];
2674 } else {
2675 if ( $isHTML ) {
2676 # Replace raw HTML by a placeholder
2677 # Add a blank line preceding, to prevent it from mucking up
2678 # immediately preceding headings
2679 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState );
2680 } else {
2681 # replace ==section headers==
2682 # XXX this needs to go away once we have a better parser.
2683 if ( $this->mOutputType != OT_WIKI && $replaceHeadings ) {
2684 if( !is_null( $title ) )
2685 $encodedname = base64_encode($title->getPrefixedDBkey());
2686 else
2687 $encodedname = base64_encode("");
2688 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2689 PREG_SPLIT_DELIM_CAPTURE);
2690 $text = '';
2691 $nsec = 0;
2692 for( $i = 0; $i < count($m); $i += 2 ) {
2693 $text .= $m[$i];
2694 if (!isset($m[$i + 1]) || $m[$i + 1] == "") continue;
2695 $hl = $m[$i + 1];
2696 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2697 $text .= $hl;
2698 continue;
2699 }
2700 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2701 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2702 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2703
2704 $nsec++;
2705 }
2706 }
2707 }
2708 }
2709
2710 # Prune lower levels off the recursion check path
2711 $this->mTemplatePath = $lastPathLevel;
2712
2713 if ( !$found ) {
2714 wfProfileOut( $fname );
2715 return $piece['text'];
2716 } else {
2717 wfProfileOut( $fname );
2718 return $text;
2719 }
2720 }
2721
2722 /**
2723 * Fetch the unparsed text of a template and register a reference to it.
2724 */
2725 function fetchTemplate( $title ) {
2726 $text = false;
2727 // Loop to fetch the article, with up to 1 redirect
2728 for ( $i = 0; $i < 2 && is_object( $title ); $i++ ) {
2729 $rev = Revision::newFromTitle( $title );
2730 $this->mOutput->addTemplate( $title, $title->getArticleID() );
2731 if ( !$rev ) {
2732 break;
2733 }
2734 $text = $rev->getText();
2735 if ( $text === false ) {
2736 break;
2737 }
2738 // Redirect?
2739 $title = Title::newFromRedirect( $text );
2740 }
2741 return $text;
2742 }
2743
2744 /**
2745 * Transclude an interwiki link.
2746 */
2747 function interwikiTransclude( $title, $action ) {
2748 global $wgEnableScaryTranscluding, $wgCanonicalNamespaceNames;
2749
2750 if (!$wgEnableScaryTranscluding)
2751 return wfMsg('scarytranscludedisabled');
2752
2753 // The namespace will actually only be 0 or 10, depending on whether there was a leading :
2754 // But we'll handle it generally anyway
2755 if ( $title->getNamespace() ) {
2756 // Use the canonical namespace, which should work anywhere
2757 $articleName = $wgCanonicalNamespaceNames[$title->getNamespace()] . ':' . $title->getDBkey();
2758 } else {
2759 $articleName = $title->getDBkey();
2760 }
2761
2762 $url = str_replace('$1', urlencode($articleName), Title::getInterwikiLink($title->getInterwiki()));
2763 $url .= "?action=$action";
2764 if (strlen($url) > 255)
2765 return wfMsg('scarytranscludetoolong');
2766 return $this->fetchScaryTemplateMaybeFromCache($url);
2767 }
2768
2769 function fetchScaryTemplateMaybeFromCache($url) {
2770 global $wgTranscludeCacheExpiry;
2771 $dbr =& wfGetDB(DB_SLAVE);
2772 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
2773 array('tc_url' => $url));
2774 if ($obj) {
2775 $time = $obj->tc_time;
2776 $text = $obj->tc_contents;
2777 if ($time && time() < $time + $wgTranscludeCacheExpiry ) {
2778 return $text;
2779 }
2780 }
2781
2782 $text = wfGetHTTP($url);
2783 if (!$text)
2784 return wfMsg('scarytranscludefailed', $url);
2785
2786 $dbw =& wfGetDB(DB_MASTER);
2787 $dbw->replace('transcache', array('tc_url'), array(
2788 'tc_url' => $url,
2789 'tc_time' => time(),
2790 'tc_contents' => $text));
2791 return $text;
2792 }
2793
2794
2795 /**
2796 * Triple brace replacement -- used for template arguments
2797 * @access private
2798 */
2799 function argSubstitution( $matches ) {
2800 $arg = trim( $matches['title'] );
2801 $text = $matches['text'];
2802 $inputArgs = end( $this->mArgStack );
2803
2804 if ( array_key_exists( $arg, $inputArgs ) ) {
2805 $text = $inputArgs[$arg];
2806 } else if ($this->mOutputType == OT_HTML && null != $matches['parts'] && count($matches['parts']) > 0) {
2807 $text = $matches['parts'][0];
2808 }
2809
2810 return $text;
2811 }
2812
2813 /**
2814 * Returns true if the function is allowed to include this entity
2815 * @access private
2816 */
2817 function incrementIncludeCount( $dbk ) {
2818 if ( !array_key_exists( $dbk, $this->mIncludeCount ) ) {
2819 $this->mIncludeCount[$dbk] = 0;
2820 }
2821 if ( ++$this->mIncludeCount[$dbk] <= MAX_INCLUDE_REPEAT ) {
2822 return true;
2823 } else {
2824 return false;
2825 }
2826 }
2827
2828 /**
2829 * This function accomplishes several tasks:
2830 * 1) Auto-number headings if that option is enabled
2831 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2832 * 3) Add a Table of contents on the top for users who have enabled the option
2833 * 4) Auto-anchor headings
2834 *
2835 * It loops through all headlines, collects the necessary data, then splits up the
2836 * string and re-inserts the newly formatted headlines.
2837 *
2838 * @param string $text
2839 * @param boolean $isMain
2840 * @access private
2841 */
2842 function formatHeadings( $text, $isMain=true ) {
2843 global $wgMaxTocLevel, $wgContLang;
2844
2845 $doNumberHeadings = $this->mOptions->getNumberHeadings();
2846 $doShowToc = true;
2847 $forceTocHere = false;
2848 if( !$this->mTitle->userCanEdit() ) {
2849 $showEditLink = 0;
2850 } else {
2851 $showEditLink = $this->mOptions->getEditSection();
2852 }
2853
2854 # Inhibit editsection links if requested in the page
2855 $esw =& MagicWord::get( MAG_NOEDITSECTION );
2856 if( $esw->matchAndRemove( $text ) ) {
2857 $showEditLink = 0;
2858 }
2859 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2860 # do not add TOC
2861 $mw =& MagicWord::get( MAG_NOTOC );
2862 if( $mw->matchAndRemove( $text ) ) {
2863 $doShowToc = false;
2864 }
2865
2866 # Get all headlines for numbering them and adding funky stuff like [edit]
2867 # links - this is for later, but we need the number of headlines right now
2868 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2869
2870 # if there are fewer than 4 headlines in the article, do not show TOC
2871 if( $numMatches < 4 ) {
2872 $doShowToc = false;
2873 }
2874
2875 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2876 # override above conditions and always show TOC at that place
2877
2878 $mw =& MagicWord::get( MAG_TOC );
2879 if($mw->match( $text ) ) {
2880 $doShowToc = true;
2881 $forceTocHere = true;
2882 } else {
2883 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2884 # override above conditions and always show TOC above first header
2885 $mw =& MagicWord::get( MAG_FORCETOC );
2886 if ($mw->matchAndRemove( $text ) ) {
2887 $doShowToc = true;
2888 }
2889 }
2890
2891 # Never ever show TOC if no headers
2892 if( $numMatches < 1 ) {
2893 $doShowToc = false;
2894 }
2895
2896 # We need this to perform operations on the HTML
2897 $sk =& $this->mOptions->getSkin();
2898
2899 # headline counter
2900 $headlineCount = 0;
2901 $sectionCount = 0; # headlineCount excluding template sections
2902
2903 # Ugh .. the TOC should have neat indentation levels which can be
2904 # passed to the skin functions. These are determined here
2905 $toc = '';
2906 $full = '';
2907 $head = array();
2908 $sublevelCount = array();
2909 $levelCount = array();
2910 $toclevel = 0;
2911 $level = 0;
2912 $prevlevel = 0;
2913 $toclevel = 0;
2914 $prevtoclevel = 0;
2915
2916 foreach( $matches[3] as $headline ) {
2917 $istemplate = 0;
2918 $templatetitle = '';
2919 $templatesection = 0;
2920 $numbering = '';
2921
2922 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2923 $istemplate = 1;
2924 $templatetitle = base64_decode($mat[1]);
2925 $templatesection = 1 + (int)base64_decode($mat[2]);
2926 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2927 }
2928
2929 if( $toclevel ) {
2930 $prevlevel = $level;
2931 $prevtoclevel = $toclevel;
2932 }
2933 $level = $matches[1][$headlineCount];
2934
2935 if( $doNumberHeadings || $doShowToc ) {
2936
2937 if ( $level > $prevlevel ) {
2938 # Increase TOC level
2939 $toclevel++;
2940 $sublevelCount[$toclevel] = 0;
2941 $toc .= $sk->tocIndent();
2942 }
2943 elseif ( $level < $prevlevel && $toclevel > 1 ) {
2944 # Decrease TOC level, find level to jump to
2945
2946 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
2947 # Can only go down to level 1
2948 $toclevel = 1;
2949 } else {
2950 for ($i = $toclevel; $i > 0; $i--) {
2951 if ( $levelCount[$i] == $level ) {
2952 # Found last matching level
2953 $toclevel = $i;
2954 break;
2955 }
2956 elseif ( $levelCount[$i] < $level ) {
2957 # Found first matching level below current level
2958 $toclevel = $i + 1;
2959 break;
2960 }
2961 }
2962 }
2963
2964 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
2965 }
2966 else {
2967 # No change in level, end TOC line
2968 $toc .= $sk->tocLineEnd();
2969 }
2970
2971 $levelCount[$toclevel] = $level;
2972
2973 # count number of headlines for each level
2974 @$sublevelCount[$toclevel]++;
2975 $dot = 0;
2976 for( $i = 1; $i <= $toclevel; $i++ ) {
2977 if( !empty( $sublevelCount[$i] ) ) {
2978 if( $dot ) {
2979 $numbering .= '.';
2980 }
2981 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
2982 $dot = 1;
2983 }
2984 }
2985 }
2986
2987 # The canonized header is a version of the header text safe to use for links
2988 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
2989 $canonized_headline = $this->unstrip( $headline, $this->mStripState );
2990 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState );
2991
2992 # Remove link placeholders by the link text.
2993 # <!--LINK number-->
2994 # turns into
2995 # link text with suffix
2996 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
2997 "\$this->mLinkHolders['texts'][\$1]",
2998 $canonized_headline );
2999 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3000 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3001 $canonized_headline );
3002
3003 # strip out HTML
3004 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3005 $tocline = trim( $canonized_headline );
3006 $canonized_headline = Sanitizer::escapeId( $tocline );
3007 $refers[$headlineCount] = $canonized_headline;
3008
3009 # count how many in assoc. array so we can track dupes in anchors
3010 @$refers[$canonized_headline]++;
3011 $refcount[$headlineCount]=$refers[$canonized_headline];
3012
3013 # Don't number the heading if it is the only one (looks silly)
3014 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3015 # the two are different if the line contains a link
3016 $headline=$numbering . ' ' . $headline;
3017 }
3018
3019 # Create the anchor for linking from the TOC to the section
3020 $anchor = $canonized_headline;
3021 if($refcount[$headlineCount] > 1 ) {
3022 $anchor .= '_' . $refcount[$headlineCount];
3023 }
3024 if( $doShowToc && ( !isset($wgMaxTocLevel) || $toclevel<$wgMaxTocLevel ) ) {
3025 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3026 }
3027 if( $showEditLink && ( !$istemplate || $templatetitle !== "" ) ) {
3028 if ( empty( $head[$headlineCount] ) ) {
3029 $head[$headlineCount] = '';
3030 }
3031 if( $istemplate )
3032 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
3033 else
3034 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle, $sectionCount+1);
3035 }
3036
3037 # give headline the correct <h#> tag
3038 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
3039
3040 $headlineCount++;
3041 if( !$istemplate )
3042 $sectionCount++;
3043 }
3044
3045 if( $doShowToc ) {
3046 $toc .= $sk->tocUnindent( $toclevel - 1 );
3047 $toc = $sk->tocList( $toc );
3048 }
3049
3050 # split up and insert constructed headlines
3051
3052 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3053 $i = 0;
3054
3055 foreach( $blocks as $block ) {
3056 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3057 # This is the [edit] link that appears for the top block of text when
3058 # section editing is enabled
3059
3060 # Disabled because it broke block formatting
3061 # For example, a bullet point in the top line
3062 # $full .= $sk->editSectionLink(0);
3063 }
3064 $full .= $block;
3065 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
3066 # Top anchor now in skin
3067 $full = $full.$toc;
3068 }
3069
3070 if( !empty( $head[$i] ) ) {
3071 $full .= $head[$i];
3072 }
3073 $i++;
3074 }
3075 if($forceTocHere) {
3076 $mw =& MagicWord::get( MAG_TOC );
3077 return $mw->replace( $toc, $full );
3078 } else {
3079 return $full;
3080 }
3081 }
3082
3083 /**
3084 * Return an HTML link for the "ISBN 123456" text
3085 * @access private
3086 */
3087 function magicISBN( $text ) {
3088 $fname = 'Parser::magicISBN';
3089 wfProfileIn( $fname );
3090
3091 $a = split( 'ISBN ', ' '.$text );
3092 if ( count ( $a ) < 2 ) {
3093 wfProfileOut( $fname );
3094 return $text;
3095 }
3096 $text = substr( array_shift( $a ), 1);
3097 $valid = '0123456789-Xx';
3098
3099 foreach ( $a as $x ) {
3100 $isbn = $blank = '' ;
3101 while ( ' ' == $x{0} ) {
3102 $blank .= ' ';
3103 $x = substr( $x, 1 );
3104 }
3105 if ( $x == '' ) { # blank isbn
3106 $text .= "ISBN $blank";
3107 continue;
3108 }
3109 while ( strstr( $valid, $x{0} ) != false ) {
3110 $isbn .= $x{0};
3111 $x = substr( $x, 1 );
3112 }
3113 $num = str_replace( '-', '', $isbn );
3114 $num = str_replace( ' ', '', $num );
3115 $num = str_replace( 'x', 'X', $num );
3116
3117 if ( '' == $num ) {
3118 $text .= "ISBN $blank$x";
3119 } else {
3120 $titleObj = Title::makeTitle( NS_SPECIAL, 'Booksources' );
3121 $text .= '<a href="' .
3122 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
3123 "\" class=\"internal\">ISBN $isbn</a>";
3124 $text .= $x;
3125 }
3126 }
3127 wfProfileOut( $fname );
3128 return $text;
3129 }
3130
3131 /**
3132 * Return an HTML link for the "RFC 1234" text
3133 *
3134 * @access private
3135 * @param string $text Text to be processed
3136 * @param string $keyword Magic keyword to use (default RFC)
3137 * @param string $urlmsg Interface message to use (default rfcurl)
3138 * @return string
3139 */
3140 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
3141
3142 $valid = '0123456789';
3143 $internal = false;
3144
3145 $a = split( $keyword, ' '.$text );
3146 if ( count ( $a ) < 2 ) {
3147 return $text;
3148 }
3149 $text = substr( array_shift( $a ), 1);
3150
3151 /* Check if keyword is preceed by [[.
3152 * This test is made here cause of the array_shift above
3153 * that prevent the test to be done in the foreach.
3154 */
3155 if ( substr( $text, -2 ) == '[[' ) {
3156 $internal = true;
3157 }
3158
3159 foreach ( $a as $x ) {
3160 /* token might be empty if we have RFC RFC 1234 */
3161 if ( $x=='' ) {
3162 $text.=$keyword;
3163 continue;
3164 }
3165
3166 $id = $blank = '' ;
3167
3168 /** remove and save whitespaces in $blank */
3169 while ( $x{0} == ' ' ) {
3170 $blank .= ' ';
3171 $x = substr( $x, 1 );
3172 }
3173
3174 /** remove and save the rfc number in $id */
3175 while ( strstr( $valid, $x{0} ) != false ) {
3176 $id .= $x{0};
3177 $x = substr( $x, 1 );
3178 }
3179
3180 if ( $id == '' ) {
3181 /* call back stripped spaces*/
3182 $text .= $keyword.$blank.$x;
3183 } elseif( $internal ) {
3184 /* normal link */
3185 $text .= $keyword.$id.$x;
3186 } else {
3187 /* build the external link*/
3188 $url = wfMsg( $urlmsg, $id);
3189 $sk =& $this->mOptions->getSkin();
3190 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
3191 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
3192 }
3193
3194 /* Check if the next RFC keyword is preceed by [[ */
3195 $internal = ( substr($x,-2) == '[[' );
3196 }
3197 return $text;
3198 }
3199
3200 /**
3201 * Transform wiki markup when saving a page by doing \r\n -> \n
3202 * conversion, substitting signatures, {{subst:}} templates, etc.
3203 *
3204 * @param string $text the text to transform
3205 * @param Title &$title the Title object for the current article
3206 * @param User &$user the User object describing the current user
3207 * @param ParserOptions $options parsing options
3208 * @param bool $clearState whether to clear the parser state first
3209 * @return string the altered wiki markup
3210 * @access public
3211 */
3212 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3213 $this->mOptions = $options;
3214 $this->mTitle =& $title;
3215 $this->mOutputType = OT_WIKI;
3216
3217 if ( $clearState ) {
3218 $this->clearState();
3219 }
3220
3221 $stripState = false;
3222 $pairs = array(
3223 "\r\n" => "\n",
3224 );
3225 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3226 $text = $this->strip( $text, $stripState, true );
3227 $text = $this->pstPass2( $text, $user );
3228 $text = $this->unstrip( $text, $stripState );
3229 $text = $this->unstripNoWiki( $text, $stripState );
3230 return $text;
3231 }
3232
3233 /**
3234 * Pre-save transform helper function
3235 * @access private
3236 */
3237 function pstPass2( $text, &$user ) {
3238 global $wgContLang, $wgLocaltimezone;
3239
3240 /* Note: This is the timestamp saved as hardcoded wikitext to
3241 * the database, we use $wgContLang here in order to give
3242 * everyone the same signiture and use the default one rather
3243 * than the one selected in each users preferences.
3244 */
3245 if ( isset( $wgLocaltimezone ) ) {
3246 $oldtz = getenv( 'TZ' );
3247 putenv( 'TZ='.$wgLocaltimezone );
3248 }
3249 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3250 ' (' . date( 'T' ) . ')';
3251 if ( isset( $wgLocaltimezone ) ) {
3252 putenv( 'TZ='.$oldtz );
3253 }
3254
3255 # Variable replacement
3256 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3257 $text = $this->replaceVariables( $text );
3258
3259 # Signatures
3260 $sigText = $this->getUserSig( $user );
3261 $text = strtr( $text, array(
3262 '~~~~~' => $d,
3263 '~~~~' => "$sigText $d",
3264 '~~~' => $sigText
3265 ) );
3266
3267 # Context links: [[|name]] and [[name (context)|]]
3268 #
3269 global $wgLegalTitleChars;
3270 $tc = "[$wgLegalTitleChars]";
3271 $np = str_replace( array( '(', ')' ), array( '', '' ), $tc ); # No parens
3272
3273 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3274 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
3275
3276 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
3277 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
3278 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
3279 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
3280 $context = '';
3281 $t = $this->mTitle->getText();
3282 if ( preg_match( $conpat, $t, $m ) ) {
3283 $context = $m[2];
3284 }
3285 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
3286 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
3287 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
3288
3289 if ( '' == $context ) {
3290 $text = preg_replace( $p2, '[[\\1]]', $text );
3291 } else {
3292 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
3293 }
3294
3295 # Trim trailing whitespace
3296 # MAG_END (__END__) tag allows for trailing
3297 # whitespace to be deliberately included
3298 $text = rtrim( $text );
3299 $mw =& MagicWord::get( MAG_END );
3300 $mw->matchAndRemove( $text );
3301
3302 return $text;
3303 }
3304
3305 /**
3306 * Fetch the user's signature text, if any, and normalize to
3307 * validated, ready-to-insert wikitext.
3308 *
3309 * @param User $user
3310 * @return string
3311 * @access private
3312 */
3313 function getUserSig( &$user ) {
3314 global $wgContLang;
3315
3316 $username = $user->getName();
3317 $nickname = $user->getOption( 'nickname' );
3318 $nickname = $nickname === '' ? $username : $nickname;
3319
3320 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3321 # Sig. might contain markup; validate this
3322 if( $this->validateSig( $nickname ) !== false ) {
3323 # Validated; clean up (if needed) and return it
3324 return( $this->cleanSig( $nickname ) );
3325 } else {
3326 # Failed to validate; fall back to the default
3327 $nickname = $username;
3328 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3329 }
3330 }
3331
3332 # If we're still here, make it a link to the user page
3333 $userpage = $user->getUserPage();
3334 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3335 }
3336
3337 /**
3338 * Check that the user's signature contains no bad XML
3339 *
3340 * @param string $text
3341 * @return mixed An expanded string, or false if invalid.
3342 */
3343 function validateSig( $text ) {
3344 return( wfIsWellFormedXmlFragment( $text ) ? $text : false );
3345 }
3346
3347 /**
3348 * Clean up signature text
3349 *
3350 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures
3351 * 2) Substitute all transclusions
3352 *
3353 * @param string $text
3354 * @return string Signature text
3355 */
3356 function cleanSig( $text ) {
3357 $substWord = MagicWord::get( MAG_SUBST );
3358 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3359 $substText = '{{' . $substWord->getSynonym( 0 );
3360
3361 $text = preg_replace( $substRegex, $substText, $text );
3362 $text = preg_replace( '/~{3,5}/', '', $text );
3363 $text = $this->replaceVariables( $text );
3364
3365 return $text;
3366 }
3367
3368 /**
3369 * Set up some variables which are usually set up in parse()
3370 * so that an external function can call some class members with confidence
3371 * @access public
3372 */
3373 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3374 $this->mTitle =& $title;
3375 $this->mOptions = $options;
3376 $this->mOutputType = $outputType;
3377 if ( $clearState ) {
3378 $this->clearState();
3379 }
3380 }
3381
3382 /**
3383 * Transform a MediaWiki message by replacing magic variables.
3384 *
3385 * @param string $text the text to transform
3386 * @param ParserOptions $options options
3387 * @return string the text with variables substituted
3388 * @access public
3389 */
3390 function transformMsg( $text, $options ) {
3391 global $wgTitle;
3392 static $executing = false;
3393
3394 $fname = "Parser::transformMsg";
3395
3396 # Guard against infinite recursion
3397 if ( $executing ) {
3398 return $text;
3399 }
3400 $executing = true;
3401
3402 wfProfileIn($fname);
3403
3404 $this->mTitle = $wgTitle;
3405 $this->mOptions = $options;
3406 $this->mOutputType = OT_MSG;
3407 $this->clearState();
3408 $text = $this->replaceVariables( $text );
3409
3410 $executing = false;
3411 wfProfileOut($fname);
3412 return $text;
3413 }
3414
3415 /**
3416 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3417 * Callback will be called with the text within
3418 * Transform and return the text within
3419 *
3420 * @access public
3421 *
3422 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3423 * @param mixed $callback The callback function (and object) to use for the tag
3424 *
3425 * @return The old value of the mTagHooks array associated with the hook
3426 */
3427 function setHook( $tag, $callback ) {
3428 $oldVal = @$this->mTagHooks[$tag];
3429 $this->mTagHooks[$tag] = $callback;
3430
3431 return $oldVal;
3432 }
3433
3434 /**
3435 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3436 * Placeholders created in Skin::makeLinkObj()
3437 * Returns an array of links found, indexed by PDBK:
3438 * 0 - broken
3439 * 1 - normal link
3440 * 2 - stub
3441 * $options is a bit field, RLH_FOR_UPDATE to select for update
3442 */
3443 function replaceLinkHolders( &$text, $options = 0 ) {
3444 global $wgUser;
3445 global $wgOutputReplace;
3446
3447 $fname = 'Parser::replaceLinkHolders';
3448 wfProfileIn( $fname );
3449
3450 $pdbks = array();
3451 $colours = array();
3452 $sk =& $this->mOptions->getSkin();
3453 $linkCache =& LinkCache::singleton();
3454
3455 if ( !empty( $this->mLinkHolders['namespaces'] ) ) {
3456 wfProfileIn( $fname.'-check' );
3457 $dbr =& wfGetDB( DB_SLAVE );
3458 $page = $dbr->tableName( 'page' );
3459 $threshold = $wgUser->getOption('stubthreshold');
3460
3461 # Sort by namespace
3462 asort( $this->mLinkHolders['namespaces'] );
3463
3464 # Generate query
3465 $query = false;
3466 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
3467 # Make title object
3468 $title = $this->mLinkHolders['titles'][$key];
3469
3470 # Skip invalid entries.
3471 # Result will be ugly, but prevents crash.
3472 if ( is_null( $title ) ) {
3473 continue;
3474 }
3475 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3476
3477 # Check if it's a static known link, e.g. interwiki
3478 if ( $title->isAlwaysKnown() ) {
3479 $colours[$pdbk] = 1;
3480 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3481 $colours[$pdbk] = 1;
3482 $this->mOutput->addLink( $title, $id );
3483 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3484 $colours[$pdbk] = 0;
3485 } else {
3486 # Not in the link cache, add it to the query
3487 if ( !isset( $current ) ) {
3488 $current = $ns;
3489 $query = "SELECT page_id, page_namespace, page_title";
3490 if ( $threshold > 0 ) {
3491 $query .= ', page_len, page_is_redirect';
3492 }
3493 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3494 } elseif ( $current != $ns ) {
3495 $current = $ns;
3496 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
3497 } else {
3498 $query .= ', ';
3499 }
3500
3501 $query .= $dbr->addQuotes( $this->mLinkHolders['dbkeys'][$key] );
3502 }
3503 }
3504 if ( $query ) {
3505 $query .= '))';
3506 if ( $options & RLH_FOR_UPDATE ) {
3507 $query .= ' FOR UPDATE';
3508 }
3509
3510 $res = $dbr->query( $query, $fname );
3511
3512 # Fetch data and form into an associative array
3513 # non-existent = broken
3514 # 1 = known
3515 # 2 = stub
3516 while ( $s = $dbr->fetchObject($res) ) {
3517 $title = Title::makeTitle( $s->page_namespace, $s->page_title );
3518 $pdbk = $title->getPrefixedDBkey();
3519 $linkCache->addGoodLinkObj( $s->page_id, $title );
3520 $this->mOutput->addLink( $title, $s->page_id );
3521
3522 if ( $threshold > 0 ) {
3523 $size = $s->page_len;
3524 if ( $s->page_is_redirect || $s->page_namespace != 0 || $size >= $threshold ) {
3525 $colours[$pdbk] = 1;
3526 } else {
3527 $colours[$pdbk] = 2;
3528 }
3529 } else {
3530 $colours[$pdbk] = 1;
3531 }
3532 }
3533 }
3534 wfProfileOut( $fname.'-check' );
3535
3536 # Construct search and replace arrays
3537 wfProfileIn( $fname.'-construct' );
3538 $wgOutputReplace = array();
3539 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
3540 $pdbk = $pdbks[$key];
3541 $searchkey = "<!--LINK $key-->";
3542 $title = $this->mLinkHolders['titles'][$key];
3543 if ( empty( $colours[$pdbk] ) ) {
3544 $linkCache->addBadLinkObj( $title );
3545 $colours[$pdbk] = 0;
3546 $this->mOutput->addLink( $title, 0 );
3547 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3548 $this->mLinkHolders['texts'][$key],
3549 $this->mLinkHolders['queries'][$key] );
3550 } elseif ( $colours[$pdbk] == 1 ) {
3551 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3552 $this->mLinkHolders['texts'][$key],
3553 $this->mLinkHolders['queries'][$key] );
3554 } elseif ( $colours[$pdbk] == 2 ) {
3555 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3556 $this->mLinkHolders['texts'][$key],
3557 $this->mLinkHolders['queries'][$key] );
3558 }
3559 }
3560 wfProfileOut( $fname.'-construct' );
3561
3562 # Do the thing
3563 wfProfileIn( $fname.'-replace' );
3564
3565 $text = preg_replace_callback(
3566 '/(<!--LINK .*?-->)/',
3567 "wfOutputReplaceMatches",
3568 $text);
3569
3570 wfProfileOut( $fname.'-replace' );
3571 }
3572
3573 # Now process interwiki link holders
3574 # This is quite a bit simpler than internal links
3575 if ( !empty( $this->mInterwikiLinkHolders['texts'] ) ) {
3576 wfProfileIn( $fname.'-interwiki' );
3577 # Make interwiki link HTML
3578 $wgOutputReplace = array();
3579 foreach( $this->mInterwikiLinkHolders['texts'] as $key => $link ) {
3580 $title = $this->mInterwikiLinkHolders['titles'][$key];
3581 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3582 }
3583
3584 $text = preg_replace_callback(
3585 '/<!--IWLINK (.*?)-->/',
3586 "wfOutputReplaceMatches",
3587 $text );
3588 wfProfileOut( $fname.'-interwiki' );
3589 }
3590
3591 wfProfileOut( $fname );
3592 return $colours;
3593 }
3594
3595 /**
3596 * Replace <!--LINK--> link placeholders with plain text of links
3597 * (not HTML-formatted).
3598 * @param string $text
3599 * @return string
3600 */
3601 function replaceLinkHoldersText( $text ) {
3602 global $wgUser;
3603 global $wgOutputReplace;
3604
3605 $fname = 'Parser::replaceLinkHoldersText';
3606 wfProfileIn( $fname );
3607
3608 $text = preg_replace_callback(
3609 '/<!--(LINK|IWLINK) (.*?)-->/',
3610 array( &$this, 'replaceLinkHoldersTextCallback' ),
3611 $text );
3612
3613 wfProfileOut( $fname );
3614 return $text;
3615 }
3616
3617 /**
3618 * @param array $matches
3619 * @return string
3620 * @access private
3621 */
3622 function replaceLinkHoldersTextCallback( $matches ) {
3623 $type = $matches[1];
3624 $key = $matches[2];
3625 if( $type == 'LINK' ) {
3626 if( isset( $this->mLinkHolders['texts'][$key] ) ) {
3627 return $this->mLinkHolders['texts'][$key];
3628 }
3629 } elseif( $type == 'IWLINK' ) {
3630 if( isset( $this->mInterwikiLinkHolders['texts'][$key] ) ) {
3631 return $this->mInterwikiLinkHolders['texts'][$key];
3632 }
3633 }
3634 return $matches[0];
3635 }
3636
3637 /**
3638 * Renders an image gallery from a text with one line per image.
3639 * text labels may be given by using |-style alternative text. E.g.
3640 * Image:one.jpg|The number "1"
3641 * Image:tree.jpg|A tree
3642 * given as text will return the HTML of a gallery with two images,
3643 * labeled 'The number "1"' and
3644 * 'A tree'.
3645 */
3646 function renderImageGallery( $text ) {
3647 # Setup the parser
3648 $parserOptions = new ParserOptions;
3649 $localParser = new Parser();
3650
3651 $ig = new ImageGallery();
3652 $ig->setShowBytes( false );
3653 $ig->setShowFilename( false );
3654 $lines = explode( "\n", $text );
3655
3656 foreach ( $lines as $line ) {
3657 # match lines like these:
3658 # Image:someimage.jpg|This is some image
3659 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3660 # Skip empty lines
3661 if ( count( $matches ) == 0 ) {
3662 continue;
3663 }
3664 $nt =& Title::newFromText( $matches[1] );
3665 if( is_null( $nt ) ) {
3666 # Bogus title. Ignore these so we don't bomb out later.
3667 continue;
3668 }
3669 if ( isset( $matches[3] ) ) {
3670 $label = $matches[3];
3671 } else {
3672 $label = '';
3673 }
3674
3675 $pout = $localParser->parse( $label , $this->mTitle, $parserOptions );
3676 $html = $pout->getText();
3677
3678 $ig->add( new Image( $nt ), $html );
3679 $this->mOutput->addImage( $nt->getDBkey() );
3680 }
3681 return $ig->toHTML();
3682 }
3683
3684 /**
3685 * Parse image options text and use it to make an image
3686 */
3687 function makeImage( &$nt, $options ) {
3688 global $wgContLang, $wgUseImageResize, $wgUser;
3689
3690 $align = '';
3691
3692 # Check if the options text is of the form "options|alt text"
3693 # Options are:
3694 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
3695 # * left no resizing, just left align. label is used for alt= only
3696 # * right same, but right aligned
3697 # * none same, but not aligned
3698 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
3699 # * center center the image
3700 # * framed Keep original image size, no magnify-button.
3701
3702 $part = explode( '|', $options);
3703
3704 $mwThumb =& MagicWord::get( MAG_IMG_THUMBNAIL );
3705 $mwManualThumb =& MagicWord::get( MAG_IMG_MANUALTHUMB );
3706 $mwLeft =& MagicWord::get( MAG_IMG_LEFT );
3707 $mwRight =& MagicWord::get( MAG_IMG_RIGHT );
3708 $mwNone =& MagicWord::get( MAG_IMG_NONE );
3709 $mwWidth =& MagicWord::get( MAG_IMG_WIDTH );
3710 $mwCenter =& MagicWord::get( MAG_IMG_CENTER );
3711 $mwFramed =& MagicWord::get( MAG_IMG_FRAMED );
3712 $caption = '';
3713
3714 $width = $height = $framed = $thumb = false;
3715 $manual_thumb = '' ;
3716
3717 foreach( $part as $key => $val ) {
3718 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
3719 $thumb=true;
3720 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
3721 # use manually specified thumbnail
3722 $thumb=true;
3723 $manual_thumb = $match;
3724 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
3725 # remember to set an alignment, don't render immediately
3726 $align = 'right';
3727 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
3728 # remember to set an alignment, don't render immediately
3729 $align = 'left';
3730 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
3731 # remember to set an alignment, don't render immediately
3732 $align = 'center';
3733 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
3734 # remember to set an alignment, don't render immediately
3735 $align = 'none';
3736 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
3737 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
3738 # $match is the image width in pixels
3739 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
3740 $width = intval( $m[1] );
3741 $height = intval( $m[2] );
3742 } else {
3743 $width = intval($match);
3744 }
3745 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
3746 $framed=true;
3747 } else {
3748 $caption = $val;
3749 }
3750 }
3751 # Strip bad stuff out of the alt text
3752 $alt = $this->replaceLinkHoldersText( $caption );
3753 $alt = Sanitizer::stripAllTags( $alt );
3754
3755 # Linker does the rest
3756 $sk =& $this->mOptions->getSkin();
3757 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
3758 }
3759
3760 /**
3761 * Set a flag in the output object indicating that the content is dynamic and
3762 * shouldn't be cached.
3763 */
3764 function disableCache() {
3765 $this->mOutput->mCacheTime = -1;
3766 }
3767
3768 /**#@+
3769 * Callback from the Sanitizer for expanding items found in HTML attribute
3770 * values, so they can be safely tested and escaped.
3771 * @param string $text
3772 * @param array $args
3773 * @return string
3774 * @access private
3775 */
3776 function attributeStripCallback( &$text, $args ) {
3777 $text = $this->replaceVariables( $text, $args );
3778 $text = $this->unstripForHTML( $text );
3779 return $text;
3780 }
3781
3782 function unstripForHTML( $text ) {
3783 $text = $this->unstrip( $text, $this->mStripState );
3784 $text = $this->unstripNoWiki( $text, $this->mStripState );
3785 return $text;
3786 }
3787 /**#@-*/
3788
3789 /**#@+
3790 * Accessor/mutator
3791 */
3792 function Title( $x = NULL ) { return wfSetVar( $this->mTitle, $x ); }
3793 function Options( $x = NULL ) { return wfSetVar( $this->mOptions, $x ); }
3794 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType, $x ); }
3795 /**#@-*/
3796
3797 /**#@+
3798 * Accessor
3799 */
3800 function getTags() { return array_keys( $this->mTagHooks ); }
3801 /**#@-*/
3802 }
3803
3804 /**
3805 * @todo document
3806 * @package MediaWiki
3807 */
3808 class ParserOutput
3809 {
3810 var $mText, # The output text
3811 $mLanguageLinks, # List of the full text of language links, in the order they appear
3812 $mCategories, # Map of category names to sort keys
3813 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
3814 $mCacheTime, # Timestamp on this article, or -1 for uncacheable. Used in ParserCache.
3815 $mVersion, # Compatibility check
3816 $mTitleText, # title text of the chosen language variant
3817 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
3818 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
3819 $mImages, # DB keys of the images used, in the array key only
3820 $mExternalLinks; # External link URLs, in the key only
3821
3822 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
3823 $containsOldMagic = false, $titletext = '' )
3824 {
3825 $this->mText = $text;
3826 $this->mLanguageLinks = $languageLinks;
3827 $this->mCategories = $categoryLinks;
3828 $this->mContainsOldMagic = $containsOldMagic;
3829 $this->mCacheTime = '';
3830 $this->mVersion = MW_PARSER_VERSION;
3831 $this->mTitleText = $titletext;
3832 $this->mLinks = array();
3833 $this->mTemplates = array();
3834 $this->mImages = array();
3835 $this->mExternalLinks = array();
3836 }
3837
3838 function getText() { return $this->mText; }
3839 function getLanguageLinks() { return $this->mLanguageLinks; }
3840 function getCategoryLinks() { return array_keys( $this->mCategories ); }
3841 function &getCategories() { return $this->mCategories; }
3842 function getCacheTime() { return $this->mCacheTime; }
3843 function getTitleText() { return $this->mTitleText; }
3844 function &getLinks() { return $this->mLinks; }
3845 function &getTemplates() { return $this->mTemplates; }
3846 function &getImages() { return $this->mImages; }
3847 function &getExternalLinks() { return $this->mExternalLinks; }
3848
3849 function containsOldMagic() { return $this->mContainsOldMagic; }
3850 function setText( $text ) { return wfSetVar( $this->mText, $text ); }
3851 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks, $ll ); }
3852 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories, $cl ); }
3853 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic, $com ); }
3854 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime, $t ); }
3855 function setTitleText( $t ) { return wfSetVar ($this->mTitleText, $t); }
3856
3857 function addCategory( $c, $sort ) { $this->mCategories[$c] = $sort; }
3858 function addImage( $name ) { $this->mImages[$name] = 1; }
3859 function addLanguageLink( $t ) { $this->mLanguageLinks[] = $t; }
3860 function addExternalLink( $url ) { $this->mExternalLinks[$url] = 1; }
3861
3862 function addLink( $title, $id ) {
3863 $ns = $title->getNamespace();
3864 $dbk = $title->getDBkey();
3865 if ( !isset( $this->mLinks[$ns] ) ) {
3866 $this->mLinks[$ns] = array();
3867 }
3868 $this->mLinks[$ns][$dbk] = $id;
3869 }
3870
3871 function addTemplate( $title, $id ) {
3872 $ns = $title->getNamespace();
3873 $dbk = $title->getDBkey();
3874 if ( !isset( $this->mTemplates[$ns] ) ) {
3875 $this->mTemplates[$ns] = array();
3876 }
3877 $this->mTemplates[$ns][$dbk] = $id;
3878 }
3879
3880 /**
3881 * @deprecated
3882 */
3883 /*
3884 function merge( $other ) {
3885 $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $other->mLanguageLinks );
3886 $this->mCategories = array_merge( $this->mCategories, $this->mLanguageLinks );
3887 $this->mContainsOldMagic = $this->mContainsOldMagic || $other->mContainsOldMagic;
3888 }*/
3889
3890 /**
3891 * Return true if this cached output object predates the global or
3892 * per-article cache invalidation timestamps, or if it comes from
3893 * an incompatible older version.
3894 *
3895 * @param string $touched the affected article's last touched timestamp
3896 * @return bool
3897 * @access public
3898 */
3899 function expired( $touched ) {
3900 global $wgCacheEpoch;
3901 return $this->getCacheTime() == -1 || // parser says it's uncacheable
3902 $this->getCacheTime() < $touched ||
3903 $this->getCacheTime() <= $wgCacheEpoch ||
3904 !isset( $this->mVersion ) ||
3905 version_compare( $this->mVersion, MW_PARSER_VERSION, "lt" );
3906 }
3907 }
3908
3909 /**
3910 * Set options of the Parser
3911 * @todo document
3912 * @package MediaWiki
3913 */
3914 class ParserOptions
3915 {
3916 # All variables are private
3917 var $mUseTeX; # Use texvc to expand <math> tags
3918 var $mUseDynamicDates; # Use DateFormatter to format dates
3919 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
3920 var $mAllowExternalImages; # Allow external images inline
3921 var $mAllowExternalImagesFrom; # If not, any exception?
3922 var $mSkin; # Reference to the preferred skin
3923 var $mDateFormat; # Date format index
3924 var $mEditSection; # Create "edit section" links
3925 var $mNumberHeadings; # Automatically number headings
3926 var $mAllowSpecialInclusion; # Allow inclusion of special pages
3927 var $mTidy; # Ask for tidy cleanup
3928
3929 function getUseTeX() { return $this->mUseTeX; }
3930 function getUseDynamicDates() { return $this->mUseDynamicDates; }
3931 function getInterwikiMagic() { return $this->mInterwikiMagic; }
3932 function getAllowExternalImages() { return $this->mAllowExternalImages; }
3933 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom; }
3934 function &getSkin() { return $this->mSkin; }
3935 function getDateFormat() { return $this->mDateFormat; }
3936 function getEditSection() { return $this->mEditSection; }
3937 function getNumberHeadings() { return $this->mNumberHeadings; }
3938 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion; }
3939 function getTidy() { return $this->mTidy; }
3940
3941 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX, $x ); }
3942 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates, $x ); }
3943 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic, $x ); }
3944 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages, $x ); }
3945 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom, $x ); }
3946 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat, $x ); }
3947 function setEditSection( $x ) { return wfSetVar( $this->mEditSection, $x ); }
3948 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings, $x ); }
3949 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion, $x ); }
3950 function setTidy( $x ) { return wfSetVar( $this->mTidy, $x); }
3951 function setSkin( &$x ) { $this->mSkin =& $x; }
3952
3953 function ParserOptions() {
3954 global $wgUser;
3955 $this->initialiseFromUser( $wgUser );
3956 }
3957
3958 /**
3959 * Get parser options
3960 * @static
3961 */
3962 function newFromUser( &$user ) {
3963 $popts = new ParserOptions;
3964 $popts->initialiseFromUser( $user );
3965 return $popts;
3966 }
3967
3968 /** Get user options */
3969 function initialiseFromUser( &$userInput ) {
3970 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages,
3971 $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion;
3972 $fname = 'ParserOptions::initialiseFromUser';
3973 wfProfileIn( $fname );
3974 if ( !$userInput ) {
3975 $user = new User;
3976 $user->setLoaded( true );
3977 } else {
3978 $user =& $userInput;
3979 }
3980
3981 $this->mUseTeX = $wgUseTeX;
3982 $this->mUseDynamicDates = $wgUseDynamicDates;
3983 $this->mInterwikiMagic = $wgInterwikiMagic;
3984 $this->mAllowExternalImages = $wgAllowExternalImages;
3985 $this->mAllowExternalImagesFrom = $wgAllowExternalImagesFrom;
3986 wfProfileIn( $fname.'-skin' );
3987 $this->mSkin =& $user->getSkin();
3988 wfProfileOut( $fname.'-skin' );
3989 $this->mDateFormat = $user->getOption( 'date' );
3990 $this->mEditSection = true;
3991 $this->mNumberHeadings = $user->getOption( 'numberheadings' );
3992 $this->mAllowSpecialInclusion = $wgAllowSpecialInclusion;
3993 $this->mTidy = false;
3994 wfProfileOut( $fname );
3995 }
3996 }
3997
3998 /**
3999 * Callback function used by Parser::replaceLinkHolders()
4000 * to substitute link placeholders.
4001 */
4002 function &wfOutputReplaceMatches( $matches ) {
4003 global $wgOutputReplace;
4004 return $wgOutputReplace[$matches[1]];
4005 }
4006
4007 /**
4008 * Return the total number of articles
4009 */
4010 function wfNumberOfArticles() {
4011 global $wgNumberOfArticles;
4012
4013 wfLoadSiteStats();
4014 return $wgNumberOfArticles;
4015 }
4016
4017 /**
4018 * Return the number of files
4019 */
4020 function wfNumberOfFiles() {
4021 $fname = 'Parser::wfNumberOfFiles';
4022
4023 wfProfileIn( $fname );
4024 $dbr =& wfGetDB( DB_SLAVE );
4025 $res = $dbr->selectField('image', 'COUNT(*)', array(), $fname );
4026 wfProfileOut( $fname );
4027
4028 return $res;
4029 }
4030
4031 /**
4032 * Get various statistics from the database
4033 * @access private
4034 */
4035 function wfLoadSiteStats() {
4036 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
4037 $fname = 'wfLoadSiteStats';
4038
4039 if ( -1 != $wgNumberOfArticles ) return;
4040 $dbr =& wfGetDB( DB_SLAVE );
4041 $s = $dbr->selectRow( 'site_stats',
4042 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
4043 array( 'ss_row_id' => 1 ), $fname
4044 );
4045
4046 if ( $s === false ) {
4047 return;
4048 } else {
4049 $wgTotalViews = $s->ss_total_views;
4050 $wgTotalEdits = $s->ss_total_edits;
4051 $wgNumberOfArticles = $s->ss_good_articles;
4052 }
4053 }
4054
4055 /**
4056 * Escape html tags
4057 * Basically replacing " > and < with HTML entities ( &quot;, &gt;, &lt;)
4058 *
4059 * @param string $in Text that might contain HTML tags
4060 * @return string Escaped string
4061 */
4062 function wfEscapeHTMLTagsOnly( $in ) {
4063 return str_replace(
4064 array( '"', '>', '<' ),
4065 array( '&quot;', '&gt;', '&lt;' ),
4066 $in );
4067 }
4068
4069 ?>